OpenID Connect (OIDC) & OAuth2 client library for TypeScript/JavaScript applications
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Low-level OIDC/OAuth2 protocol support providing raw protocol implementation for authorization and token endpoints. Use this class when you need direct protocol control without the additional management features of UserManager.
Provides the raw OIDC/OAuth2 protocol support for authorization and end session endpoints.
/**
* Provides raw OIDC/OAuth2 protocol support for authorization and end session endpoints.
* Only use this class if you simply want protocol support without the additional
* management features of the UserManager class.
*/
class OidcClient {
constructor(settings: OidcClientSettings);
constructor(settings: OidcClientSettingsStore, metadataService: MetadataService);
/** The settings used to configure the OidcClient */
readonly settings: OidcClientSettingsStore;
/** Service for retrieving OIDC provider metadata */
readonly metadataService: MetadataService;
}Create an authorization request for the OIDC provider.
/**
* Create a signin request to send to the authorization endpoint
* @param args - Arguments for creating the signin request
* @returns Promise containing the signin request
*/
createSigninRequest(args: CreateSigninRequestArgs): Promise<SigninRequest>;
interface CreateSigninRequestArgs {
/** Override the redirect URI */
redirect_uri?: string;
/** Override the response type */
response_type?: string;
/** Override the scope */
scope?: string;
/** DPoP JWT key thumbprint for binding */
dpopJkt?: string;
/** Custom state data to round-trip */
state?: unknown;
// Optional OIDC parameters
nonce?: string;
prompt?: string;
display?: string;
max_age?: number;
ui_locales?: string;
id_token_hint?: string;
login_hint?: string;
acr_values?: string;
resource?: string | string[];
// Request object parameters
request?: string;
request_uri?: string;
request_type?: string;
// Additional parameters
extraQueryParams?: Record<string, string | number | boolean>;
extraTokenParams?: Record<string, unknown>;
url_state?: boolean;
}
class SigninRequest {
constructor(args: SigninRequestCreateArgs);
/** The complete authorization URL */
readonly url: string;
/** The state parameter for this request */
readonly state: State;
}Process the callback response from the authorization endpoint.
/**
* Process the response from the authorization endpoint
* @param url - The callback URL containing the authorization response
* @returns Promise containing the signin response
*/
processSigninResponse(url: string): Promise<SigninResponse>;
class SigninResponse {
constructor(url: string);
/** The authorization code (for code flow) */
readonly code?: string;
/** The state parameter from the request */
readonly state?: string;
/** Error code if the request failed */
readonly error?: string;
/** Error description if available */
readonly error_description?: string;
/** Session state for session management */
readonly session_state?: string;
/** The access token (for implicit flow) */
readonly access_token?: string;
/** The ID token */
readonly id_token?: string;
/** The token type */
readonly token_type?: string;
/** The scope granted by the authorization server */
readonly scope?: string;
/** Token expiration time in seconds */
readonly expires_in?: number;
/** The user profile extracted from the ID token */
readonly profile?: UserProfile;
/** When the access token expires */
readonly expires_at?: number;
/** Whether the access token has expired */
readonly expired: boolean;
/** Array of granted scopes */
readonly scopes: string[];
}Exchange a refresh token for new tokens.
/**
* Use a refresh token to obtain a new access token
* @param args - Arguments for the refresh token request
* @returns Promise containing the token response
*/
useRefreshToken(args: UseRefreshTokenArgs): Promise<SigninResponse>;
interface UseRefreshTokenArgs {
/** Override the redirect URI */
redirect_uri?: string;
/** Resource indicators for the requested access token */
resource?: string | string[];
/** Additional parameters for the token request */
extraTokenParams?: Record<string, unknown>;
/** Request timeout in seconds */
timeoutInSeconds?: number;
/** The refresh state containing the refresh token */
state: RefreshState;
/** Additional headers for the token request */
extraHeaders?: Record<string, ExtraHeader>;
}
interface RefreshState {
/** The refresh token */
refresh_token: string;
/** The ID token hint */
id_token_hint?: string;
/** Session state */
session_state?: string;
/** Custom data */
data?: unknown;
}Perform resource owner password credentials grant (not recommended for browser apps).
/**
* Process resource owner password credentials (ROPC) grant
* @param args - Username and password credentials
* @returns Promise containing the token response
*/
processResourceOwnerPasswordCredentials(args: ProcessResourceOwnerPasswordCredentialsArgs): Promise<SigninResponse>;
interface ProcessResourceOwnerPasswordCredentialsArgs {
/** The username */
username: string;
/** The password */
password: string;
/** Skip loading user info from the userinfo endpoint */
skipUserInfo?: boolean;
/** Additional parameters for the token request */
extraTokenParams?: Record<string, unknown>;
}Create an end session request.
/**
* Create a signout request to send to the end session endpoint
* @param args - Arguments for creating the signout request (optional)
* @returns Promise containing the signout request
*/
createSignoutRequest(args?: CreateSignoutRequestArgs): Promise<SignoutRequest>;
interface CreateSignoutRequestArgs {
/** Custom state data to round-trip */
state?: unknown;
/** ID token hint for the signout request */
id_token_hint?: string;
/** Override the post logout redirect URI */
post_logout_redirect_uri?: string;
/** Additional query parameters for the end session request */
extraQueryParams?: Record<string, string | number | boolean>;
/** Custom URL state parameter */
url_state?: boolean;
}
class SignoutRequest {
constructor(args: SignoutRequestArgs);
/** The complete end session URL */
readonly url: string;
/** The state parameter for this request */
readonly state?: State;
}Process the callback response from the end session endpoint.
/**
* Process the response from the end session endpoint
* @param url - The callback URL containing the signout response
* @returns Promise containing the signout response
*/
processSignoutResponse(url: string): Promise<SignoutResponse>;
class SignoutResponse {
constructor(url: string);
/** The state parameter from the request */
readonly state?: string;
/** Error code if the request failed */
readonly error?: string;
/** Error description if available */
readonly error_description?: string;
}import { OidcClient } from "oidc-client-ts";
const client = new OidcClient({
authority: "https://demo.identityserver.io",
client_id: "interactive.public",
redirect_uri: "http://localhost:5000/callback",
response_type: "code",
scope: "openid profile email",
});
// Create signin request
const signinRequest = await client.createSigninRequest({
state: { returnUrl: "/dashboard" },
});
// Redirect user to authorization endpoint
window.location.href = signinRequest.url;
// In callback handler
const signinResponse = await client.processSigninResponse(window.location.href);
if (signinResponse.error) {
console.error("Authorization failed:", signinResponse.error_description);
} else {
console.log("Authorization successful:", signinResponse.profile);
}// Assuming you have a refresh token from a previous authentication
const refreshState = {
refresh_token: "your-refresh-token",
id_token_hint: "previous-id-token",
};
try {
const refreshResponse = await client.useRefreshToken({
state: refreshState,
resource: ["api1", "api2"],
});
console.log("Tokens refreshed:", {
access_token: refreshResponse.access_token,
expires_in: refreshResponse.expires_in,
});
} catch (error) {
console.error("Token refresh failed:", error);
}// Create signout request
const signoutRequest = await client.createSignoutRequest({
id_token_hint: "current-id-token",
state: { message: "User initiated signout" },
});
// Redirect to end session endpoint
window.location.href = signoutRequest.url;
// In signout callback handler
const signoutResponse = await client.processSignoutResponse(window.location.href);
if (signoutResponse.error) {
console.error("Signout error:", signoutResponse.error_description);
} else {
console.log("Signout successful");
}// Create signin request with custom parameters
const signinRequest = await client.createSigninRequest({
scope: "openid profile email offline_access",
acr_values: "urn:mace:incommon:iap:silver",
login_hint: "user@example.com",
max_age: 3600,
extraQueryParams: {
tenant: "contoso",
domain_hint: "contoso.com",
},
extraTokenParams: {
resource: "https://graph.microsoft.com",
},
});The OidcClient works closely with the MetadataService to automatically discover provider configuration.
class MetadataService {
constructor(settings: OidcClientSettingsStore);
/** Get the provider's metadata */
getMetadata(): Promise<OidcMetadata>;
/** Get the provider's signing keys */
getSigningKeys(): Promise<SigningKey[]>;
/** Get a specific endpoint URL */
getAuthorizationEndpoint(): Promise<string>;
getTokenEndpoint(): Promise<string>;
getUserInfoEndpoint(): Promise<string>;
getEndSessionEndpoint(): Promise<string>;
getCheckSessionIframe(): Promise<string | undefined>;
getRevocationEndpoint(): Promise<string | undefined>;
getIntrospectionEndpoint(): Promise<string | undefined>;
}Advanced Usage with Custom Metadata:
import { OidcClient, MetadataService } from "oidc-client-ts";
// Create client with custom metadata service
const settings = {
authority: "https://custom-provider.com",
client_id: "my-client",
redirect_uri: "http://localhost:5000/callback",
// Provide metadata when CORS is not available
metadata: {
authorization_endpoint: "https://custom-provider.com/oauth/authorize",
token_endpoint: "https://custom-provider.com/oauth/token",
userinfo_endpoint: "https://custom-provider.com/oauth/userinfo",
end_session_endpoint: "https://custom-provider.com/oauth/logout",
issuer: "https://custom-provider.com",
},
};
const metadataService = new MetadataService(settings);
const client = new OidcClient(settings, metadataService);Install with Tessl CLI
npx tessl i tessl/npm-oidc-client-ts