OAuth 2.0 and OpenID Connect client library for JavaScript runtimes with comprehensive authentication flows and security features.
npx @tessl/cli install tessl/npm-openid-client@6.7.0OpenID Client is a comprehensive OAuth 2.0 and OpenID Connect client library for JavaScript runtimes. It provides complete support for all major authentication flows, advanced security features like FAPI compliance, DPoP, JARM, JAR, and PAR, with extensive configuration options for Node.js, browsers, Deno, Cloudflare Workers, and other JavaScript environments.
npm install openid-clientimport * as client from "openid-client";For specific imports:
import {
discovery,
Configuration,
authorizationCodeGrant,
buildAuthorizationUrl,
ClientSecretPost
} from "openid-client";For Passport.js integration:
import { Strategy } from "openid-client/passport";For CommonJS:
const client = require("openid-client");For specific CommonJS imports:
const {
discovery,
Configuration,
authorizationCodeGrant,
buildAuthorizationUrl,
ClientSecretPost
} = require("openid-client");import * as client from "openid-client";
// 1. Discover authorization server configuration
const config = await client.discovery(
new URL("https://accounts.google.com"), // issuer
"your-client-id", // client ID
"your-client-secret" // client secret (or client metadata object)
);
// 2. Build authorization URL with PKCE
const codeVerifier = client.randomPKCECodeVerifier();
const codeChallenge = await client.calculatePKCECodeChallenge(codeVerifier);
const authUrl = client.buildAuthorizationUrl(config, {
redirect_uri: "https://example.com/callback",
scope: "openid email profile",
code_challenge: codeChallenge,
code_challenge_method: "S256",
state: client.randomState(),
nonce: client.randomNonce()
});
// 3. Handle authorization callback
const tokens = await client.authorizationCodeGrant(
config,
currentUrl, // URL with authorization response parameters
{
pkceCodeVerifier: codeVerifier,
expectedState: expectedState,
expectedNonce: expectedNonce
}
);
// 4. Access tokens and claims
console.log("Access Token:", tokens.access_token);
console.log("ID Token Claims:", tokens.claims());
console.log("Expires in:", tokens.expiresIn(), "seconds");
// 5. Fetch user info
const userInfo = await client.fetchUserInfo(
config,
tokens.access_token,
tokens.claims()?.sub // expected subject
);OpenID Client is built around several key components:
Configuration class combining server and client metadata with automatic discovery supportCore configuration management and automatic Authorization Server metadata discovery. Essential for all OAuth/OIDC operations.
function discovery(
server: URL,
clientId: string,
metadata?: Partial<ClientMetadata> | string,
clientAuthentication?: ClientAuth,
options?: DiscoveryRequestOptions
): Promise<Configuration>;
class Configuration {
constructor(
server: ServerMetadata,
clientId: string,
metadata?: Partial<ClientMetadata> | string,
clientAuthentication?: ClientAuth
);
serverMetadata(): Readonly<ServerMetadata>;
clientMetadata(): Readonly<ClientMetadata>;
}Authorization URL building and authorization code grant processing with support for PKCE, state validation, and advanced flows.
function buildAuthorizationUrl(
config: Configuration,
parameters: URLSearchParams | Record<string, string>
): URL;
function authorizationCodeGrant(
config: Configuration,
currentUrl: URL | Request,
checks?: AuthorizationCodeGrantChecks,
tokenEndpointParameters?: URLSearchParams | Record<string, string>,
options?: AuthorizationCodeGrantOptions
): Promise<TokenEndpointResponse & TokenEndpointResponseHelpers>;All standard OAuth 2.0 client authentication methods including client secrets, private key JWT, and mutual TLS.
function ClientSecretPost(clientSecret?: string): ClientAuth;
function ClientSecretBasic(clientSecret?: string): ClientAuth;
function ClientSecretJwt(clientSecret?: string, options?: ModifyAssertionOptions): ClientAuth;
function PrivateKeyJwt(clientPrivateKey: CryptoKey | PrivateKey, options?: ModifyAssertionOptions): ClientAuth;
function TlsClientAuth(): ClientAuth;
function None(): ClientAuth;Complete implementation of all OAuth 2.0 and OpenID Connect grant types including device flow and CIBA.
function clientCredentialsGrant(
config: Configuration,
parameters?: URLSearchParams | Record<string, string>,
options?: DPoPOptions
): Promise<TokenEndpointResponse & TokenEndpointResponseHelpers>;
function refreshTokenGrant(
config: Configuration,
refreshToken: string,
parameters?: URLSearchParams | Record<string, string>,
options?: DPoPOptions
): Promise<TokenEndpointResponse & TokenEndpointResponseHelpers>;Token introspection, revocation, and lifecycle management operations.
function tokenIntrospection(
config: Configuration,
token: string,
parameters?: URLSearchParams | Record<string, string>
): Promise<IntrospectionResponse>;
function tokenRevocation(
config: Configuration,
token: string,
parameters?: URLSearchParams | Record<string, string>
): Promise<void>;Access protected resources and UserInfo endpoint with proper access token handling.
function fetchUserInfo(
config: Configuration,
accessToken: string,
expectedSubject: string | typeof skipSubjectCheck,
options?: DPoPOptions
): Promise<UserInfoResponse>;
function fetchProtectedResource(
config: Configuration,
accessToken: string,
url: URL,
method: string,
body?: FetchBody,
headers?: Headers,
options?: DPoPOptions
): Promise<Response>;FAPI compliance, DPoP, JARM, JAR, PAR, and other advanced security mechanisms.
function getDPoPHandle(
config: Configuration,
keyPair: CryptoKeyPair,
options?: ModifyAssertionOptions
): DPoPHandle;
function useJwtResponseMode(config: Configuration): void;
function enableNonRepudiationChecks(config: Configuration): void;
function useCodeIdTokenResponseType(config: Configuration): void;Complete Passport.js strategy for OpenID Connect authentication with Express.js applications.
class Strategy implements passport.Strategy {
constructor(options: StrategyOptions, verify: VerifyFunction);
constructor(options: StrategyOptionsWithRequest, verify: VerifyFunctionWithRequest);
authenticate<TOptions extends AuthenticateOptions>(
req: express.Request,
options: TOptions
): void;
}interface ServerMetadata extends AuthorizationServer {
// Authorization Server metadata from oauth4webapi
}
interface ClientMetadata extends Client {
client_secret?: string;
use_mtls_endpoint_aliases?: boolean;
}
interface TokenEndpointResponse {
access_token: string;
token_type: string;
expires_in?: number;
refresh_token?: string;
scope?: string;
id_token?: string;
}
interface TokenEndpointResponseHelpers {
claims(): IDToken | undefined;
expiresIn(): number | undefined;
}
interface AuthorizationCodeGrantChecks {
expectedNonce?: string;
expectedState?: string | typeof skipStateCheck;
idTokenExpected?: boolean;
maxAge?: number;
pkceCodeVerifier?: string;
}
interface DPoPOptions {
DPoP?: DPoPHandle;
}
interface DPoPHandle {
// DPoP handle for proof-of-possession operations
}
type ClientAuth = (
as: ServerMetadata,
client: ClientMetadata,
body: URLSearchParams,
headers: Headers
) => void;
type CryptoKey = Extract<Awaited<ReturnType<typeof crypto.subtle.generateKey>>, {
type: string;
}>;
interface CryptoKeyPair {
privateKey: CryptoKey;
publicKey: CryptoKey;
}