OpenID Connect (OIDC) & OAuth2 client library for TypeScript/JavaScript applications
npx @tessl/cli install tessl/npm-oidc-client-ts@3.3.0OpenID Connect (OIDC) & OAuth2 client library for TypeScript/JavaScript applications. Provides comprehensive authentication and token management capabilities for browser-based applications with support for multiple authentication flows, silent token renewal, and session monitoring.
npm install oidc-client-ts// Main classes
import { UserManager, User, OidcClient } from "oidc-client-ts";
// Events and logging
import { Logger, Log, AccessTokenEvents } from "oidc-client-ts";
// Error handling
import { ErrorResponse, ErrorTimeout } from "oidc-client-ts";
// Storage and session management
import { WebStorageStateStore, InMemoryWebStorage, SessionMonitor, IndexedDbDPoPStore, DPoPState } from "oidc-client-ts";
// Advanced features
import { MetadataService, CheckSessionIFrame } from "oidc-client-ts";For CommonJS:
const {
UserManager,
User,
OidcClient,
Logger,
ErrorResponse,
WebStorageStateStore
} = require("oidc-client-ts");import { UserManager } from "oidc-client-ts";
// Configure the UserManager
const userManager = new UserManager({
authority: "https://your-oidc-provider.com",
client_id: "your-client-id",
redirect_uri: "http://localhost:3000/callback",
post_logout_redirect_uri: "http://localhost:3000",
response_type: "code",
scope: "openid profile email",
automaticSilentRenew: true,
silent_redirect_uri: "http://localhost:3000/silent-callback.html"
});
// Sign in using redirect flow
await userManager.signinRedirect();
// Handle callback and get user
const user = await userManager.signinRedirectCallback();
console.log("Authenticated user:", user.profile);
// Get current user
const currentUser = await userManager.getUser();
// Sign out
await userManager.signoutRedirect();OIDC Client TypeScript is built around several key components:
High-level user authentication and session management with automatic token renewal and event handling.
class UserManager {
constructor(settings: UserManagerSettings);
// Authentication flows
signinRedirect(args?: SigninRedirectArgs): Promise<void>;
signinPopup(args?: SigninPopupArgs): Promise<User>;
signinSilent(args?: SigninSilentArgs): Promise<User>;
signinResourceOwnerCredentials(args: SigninResourceOwnerCredentialsArgs): Promise<User>;
// Callback handling
signinRedirectCallback(url?: string): Promise<User>;
signinPopupCallback(url?: string): Promise<void>;
signinSilentCallback(url?: string): Promise<User>;
// Universal callback methods (recommended)
signinCallback(url?: string): Promise<User | undefined>;
signoutCallback(url?: string, keepOpen?: boolean): Promise<SignoutResponse | undefined>;
// Sign out flows
signoutRedirect(args?: SignoutRedirectArgs): Promise<void>;
signoutPopup(args?: SignoutPopupArgs): Promise<void>;
signoutSilent(args?: SignoutSilentArgs): Promise<void>;
// Sign out callback handling
signoutRedirectCallback(url?: string): Promise<SignoutResponse>;
signoutPopupCallback(url?: string, keepOpen?: boolean): Promise<void>;
signoutSilentCallback(url?: string): Promise<void>;
// User operations
getUser(): Promise<User | null>;
removeUser(): Promise<void>;
storeUser(user: User): Promise<void>;
// Token management
startSilentRenew(): void;
stopSilentRenew(): void;
revokeTokens(types?: RevokeTokensTypes): Promise<void>;
// Session monitoring
querySessionStatus(args?: QuerySessionStatusArgs): Promise<SessionStatus>;
// Properties
readonly settings: UserManagerSettingsStore;
readonly events: UserManagerEvents;
readonly metadataService: MetadataService;
}Low-level OIDC/OAuth2 protocol support for authorization and token endpoints.
class OidcClient {
constructor(settings: OidcClientSettings);
// Protocol operations
createSigninRequest(args: CreateSigninRequestArgs): Promise<SigninRequest>;
processSigninResponse(url: string): Promise<SigninResponse>;
createSignoutRequest(args?: CreateSignoutRequestArgs): Promise<SignoutRequest>;
processSignoutResponse(url: string): Promise<SignoutResponse>;
useRefreshToken(args: UseRefreshTokenArgs): Promise<SigninResponse>;
processResourceOwnerPasswordCredentials(args: ProcessResourceOwnerPasswordCredentialsArgs): Promise<SigninResponse>;
// Properties
readonly settings: OidcClientSettingsStore;
readonly metadataService: MetadataService;
}Configuration options for both UserManager and OidcClient with comprehensive customization.
interface UserManagerSettings extends OidcClientSettings {
// Popup configuration
popup_redirect_uri?: string;
popup_post_logout_redirect_uri?: string;
popupWindowFeatures?: PopupWindowFeatures;
// Silent renewal
silent_redirect_uri?: string;
automaticSilentRenew?: boolean;
silentRequestTimeoutInSeconds?: number;
// Session monitoring
monitorSession?: boolean;
checkSessionIntervalInSeconds?: number;
// Token management
revokeTokensOnSignout?: boolean;
revokeTokenTypes?: ("access_token" | "refresh_token")[];
// Storage
userStore?: StateStore;
}
interface OidcClientSettings {
// Required settings
authority: string;
client_id: string;
redirect_uri: string;
// Optional protocol settings
response_type?: string;
scope?: string;
post_logout_redirect_uri?: string;
client_secret?: string;
client_authentication?: "client_secret_basic" | "client_secret_post";
// Advanced settings
metadata?: Partial<OidcMetadata>;
signingKeys?: SigningKey[];
extraQueryParams?: Record<string, string | number | boolean>;
extraHeaders?: Record<string, ExtraHeader>;
stateStore?: StateStore;
dpop?: DPoPSettings;
}User profile and token data structures with comprehensive claims support.
class User {
constructor(args: {
id_token?: string;
session_state?: string;
access_token?: string;
refresh_token?: string;
token_type?: string;
scope?: string;
profile?: UserProfile;
expires_at?: number;
state?: unknown;
});
readonly id_token?: string;
readonly session_state?: string;
readonly access_token?: string;
readonly refresh_token?: string;
readonly token_type?: string;
readonly scope?: string;
readonly profile?: UserProfile;
readonly expires_at?: number;
readonly expires_in?: number;
readonly expired: boolean;
readonly scopes: string[];
readonly state?: unknown;
toStorageString(): string;
}
interface UserProfile extends IdTokenClaims {
sub: string;
name?: string;
given_name?: string;
family_name?: string;
middle_name?: string;
nickname?: string;
preferred_username?: string;
profile?: string;
picture?: string;
website?: string;
email?: string;
email_verified?: boolean;
gender?: string;
birthdate?: string;
zoneinfo?: string;
locale?: string;
phone_number?: string;
phone_number_verified?: boolean;
address?: OidcAddressClaim;
updated_at?: number;
}Comprehensive event system for user state changes, token expiration, and error handling.
class UserManagerEvents {
// Event registration
addUserLoaded(callback: UserLoadedCallback): void;
addUserUnloaded(callback: UserUnloadedCallback): void;
addUserSignedIn(callback: UserSignedInCallback): void;
addUserSignedOut(callback: UserSignedOutCallback): void;
addUserSessionChanged(callback: UserSessionChangedCallback): void;
addSilentRenewError(callback: SilentRenewErrorCallback): void;
// Event removal
removeUserLoaded(callback: UserLoadedCallback): void;
removeUserUnloaded(callback: UserUnloadedCallback): void;
removeUserSignedIn(callback: UserSignedInCallback): void;
removeUserSignedOut(callback: UserSignedOutCallback): void;
removeUserSessionChanged(callback: UserSessionChangedCallback): void;
removeSilentRenewError(callback: SilentRenewErrorCallback): void;
}
class AccessTokenEvents {
addAccessTokenExpiring(callback: AccessTokenCallback): void;
addAccessTokenExpired(callback: AccessTokenCallback): void;
removeAccessTokenExpiring(callback: AccessTokenCallback): void;
removeAccessTokenExpired(callback: AccessTokenCallback): void;
}
// Event callback types
type UserLoadedCallback = (user: User) => Promise<void> | void;
type UserUnloadedCallback = () => Promise<void> | void;
type UserSignedInCallback = () => Promise<void> | void;
type UserSignedOutCallback = () => Promise<void> | void;
type UserSessionChangedCallback = () => Promise<void> | void;
type SilentRenewErrorCallback = (error: Error) => Promise<void> | void;
type AccessTokenCallback = (...ev: unknown[]) => Promise<void> | void;Flexible storage options for user data and request state with built-in and custom implementations.
interface StateStore {
set(key: string, value: string): Promise<void>;
get(key: string): Promise<string | null>;
remove(key: string): Promise<string | null>;
getAllKeys(): Promise<string[]>;
}
class WebStorageStateStore implements StateStore {
constructor(args?: { store?: Storage; prefix?: string });
set(key: string, value: string): Promise<void>;
get(key: string): Promise<string | null>;
remove(key: string): Promise<string | null>;
getAllKeys(): Promise<string[]>;
}
class InMemoryWebStorage implements StateStore {
setItem(key: string, value: string): void;
getItem(key: string): string | null;
removeItem(key: string): void;
key(index: number): string | null;
readonly length: number;
}
// DPoP support
interface DPoPStore {
set(key: string, value: DPoPState): Promise<void>;
get(key: string): Promise<DPoPState>;
remove(key: string): Promise<DPoPState>;
getAllKeys(): Promise<string[]>;
}
class IndexedDbDPoPStore implements DPoPStore {
constructor(args?: { dbName?: string; tableName?: string });
set(key: string, value: DPoPState): Promise<void>;
get(key: string): Promise<DPoPState>;
remove(key: string): Promise<DPoPState>;
getAllKeys(): Promise<string[]>;
}Comprehensive error types for authentication failures, timeouts, and protocol errors.
class ErrorResponse extends Error {
constructor(args: {
error: string;
error_description?: string;
error_uri?: string;
state?: string;
session_state?: string;
});
readonly error: string;
readonly error_description?: string;
readonly error_uri?: string;
readonly state?: string;
readonly session_state?: string;
}
class ErrorTimeout extends Error {
constructor(message?: string);
}Utility functions for cryptography, JWT handling, URL manipulation, and configurable logging.
// Logging
class Logger {
constructor(name: string);
debug(message: string, ...args: unknown[]): void;
info(message: string, ...args: unknown[]): void;
warn(message: string, ...args: unknown[]): void;
error(message: string, ...args: unknown[]): void;
create(name: string): Logger;
}
class Log {
static NONE: number;
static ERROR: number;
static WARN: number;
static INFO: number;
static DEBUG: number;
static level: number;
static logger: Console;
}
// Utility functions
class CryptoUtils {
static generateUUIDv4(): string;
static generateCodeVerifier(): string;
static generateCodeChallenge(codeVerifier: string): Promise<string>;
static generateBasicAuth(client_id: string, client_secret: string): string;
}
class JwtUtils {
static decode(token: string): JwtClaims;
}
class UrlUtils {
static readParams(url: string, responseMode?: "query" | "fragment"): URLSearchParams;
}
// Version information
const Version: string;