0
# OIDC Client TypeScript
1
2
OpenID 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.
3
4
## Package Information
5
6
- **Package Name**: oidc-client-ts
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install oidc-client-ts`
10
11
## Core Imports
12
13
```typescript
14
// Main classes
15
import { UserManager, User, OidcClient } from "oidc-client-ts";
16
17
// Events and logging
18
import { Logger, Log, AccessTokenEvents } from "oidc-client-ts";
19
20
// Error handling
21
import { ErrorResponse, ErrorTimeout } from "oidc-client-ts";
22
23
// Storage and session management
24
import { WebStorageStateStore, InMemoryWebStorage, SessionMonitor, IndexedDbDPoPStore, DPoPState } from "oidc-client-ts";
25
26
// Advanced features
27
import { MetadataService, CheckSessionIFrame } from "oidc-client-ts";
28
```
29
30
For CommonJS:
31
32
```javascript
33
const {
34
UserManager,
35
User,
36
OidcClient,
37
Logger,
38
ErrorResponse,
39
WebStorageStateStore
40
} = require("oidc-client-ts");
41
```
42
43
## Basic Usage
44
45
```typescript
46
import { UserManager } from "oidc-client-ts";
47
48
// Configure the UserManager
49
const userManager = new UserManager({
50
authority: "https://your-oidc-provider.com",
51
client_id: "your-client-id",
52
redirect_uri: "http://localhost:3000/callback",
53
post_logout_redirect_uri: "http://localhost:3000",
54
response_type: "code",
55
scope: "openid profile email",
56
automaticSilentRenew: true,
57
silent_redirect_uri: "http://localhost:3000/silent-callback.html"
58
});
59
60
// Sign in using redirect flow
61
await userManager.signinRedirect();
62
63
// Handle callback and get user
64
const user = await userManager.signinRedirectCallback();
65
console.log("Authenticated user:", user.profile);
66
67
// Get current user
68
const currentUser = await userManager.getUser();
69
70
// Sign out
71
await userManager.signoutRedirect();
72
```
73
74
## Architecture
75
76
OIDC Client TypeScript is built around several key components:
77
78
- **UserManager**: High-level API for user authentication and session management
79
- **OidcClient**: Low-level OIDC/OAuth2 protocol implementation
80
- **User**: Represents authenticated user with profile and token information
81
- **Navigation**: Multiple authentication flows (redirect, popup, silent)
82
- **Token Management**: Automatic renewal, validation, and storage
83
- **Event System**: User state change notifications and token expiry events
84
85
## Capabilities
86
87
### User Management
88
89
High-level user authentication and session management with automatic token renewal and event handling.
90
91
```typescript { .api }
92
class UserManager {
93
constructor(settings: UserManagerSettings);
94
95
// Authentication flows
96
signinRedirect(args?: SigninRedirectArgs): Promise<void>;
97
signinPopup(args?: SigninPopupArgs): Promise<User>;
98
signinSilent(args?: SigninSilentArgs): Promise<User>;
99
signinResourceOwnerCredentials(args: SigninResourceOwnerCredentialsArgs): Promise<User>;
100
101
// Callback handling
102
signinRedirectCallback(url?: string): Promise<User>;
103
signinPopupCallback(url?: string): Promise<void>;
104
signinSilentCallback(url?: string): Promise<User>;
105
106
// Universal callback methods (recommended)
107
signinCallback(url?: string): Promise<User | undefined>;
108
signoutCallback(url?: string, keepOpen?: boolean): Promise<SignoutResponse | undefined>;
109
110
// Sign out flows
111
signoutRedirect(args?: SignoutRedirectArgs): Promise<void>;
112
signoutPopup(args?: SignoutPopupArgs): Promise<void>;
113
signoutSilent(args?: SignoutSilentArgs): Promise<void>;
114
115
// Sign out callback handling
116
signoutRedirectCallback(url?: string): Promise<SignoutResponse>;
117
signoutPopupCallback(url?: string, keepOpen?: boolean): Promise<void>;
118
signoutSilentCallback(url?: string): Promise<void>;
119
120
// User operations
121
getUser(): Promise<User | null>;
122
removeUser(): Promise<void>;
123
storeUser(user: User): Promise<void>;
124
125
// Token management
126
startSilentRenew(): void;
127
stopSilentRenew(): void;
128
revokeTokens(types?: RevokeTokensTypes): Promise<void>;
129
130
// Session monitoring
131
querySessionStatus(args?: QuerySessionStatusArgs): Promise<SessionStatus>;
132
133
// Properties
134
readonly settings: UserManagerSettingsStore;
135
readonly events: UserManagerEvents;
136
readonly metadataService: MetadataService;
137
}
138
```
139
140
[User Management](./user-management.md)
141
142
### OIDC Protocol Client
143
144
Low-level OIDC/OAuth2 protocol support for authorization and token endpoints.
145
146
```typescript { .api }
147
class OidcClient {
148
constructor(settings: OidcClientSettings);
149
150
// Protocol operations
151
createSigninRequest(args: CreateSigninRequestArgs): Promise<SigninRequest>;
152
processSigninResponse(url: string): Promise<SigninResponse>;
153
createSignoutRequest(args?: CreateSignoutRequestArgs): Promise<SignoutRequest>;
154
processSignoutResponse(url: string): Promise<SignoutResponse>;
155
useRefreshToken(args: UseRefreshTokenArgs): Promise<SigninResponse>;
156
processResourceOwnerPasswordCredentials(args: ProcessResourceOwnerPasswordCredentialsArgs): Promise<SigninResponse>;
157
158
// Properties
159
readonly settings: OidcClientSettingsStore;
160
readonly metadataService: MetadataService;
161
}
162
```
163
164
[OIDC Protocol Client](./oidc-client.md)
165
166
### Configuration and Settings
167
168
Configuration options for both UserManager and OidcClient with comprehensive customization.
169
170
```typescript { .api }
171
interface UserManagerSettings extends OidcClientSettings {
172
// Popup configuration
173
popup_redirect_uri?: string;
174
popup_post_logout_redirect_uri?: string;
175
popupWindowFeatures?: PopupWindowFeatures;
176
177
// Silent renewal
178
silent_redirect_uri?: string;
179
automaticSilentRenew?: boolean;
180
silentRequestTimeoutInSeconds?: number;
181
182
// Session monitoring
183
monitorSession?: boolean;
184
checkSessionIntervalInSeconds?: number;
185
186
// Token management
187
revokeTokensOnSignout?: boolean;
188
revokeTokenTypes?: ("access_token" | "refresh_token")[];
189
190
// Storage
191
userStore?: StateStore;
192
}
193
194
interface OidcClientSettings {
195
// Required settings
196
authority: string;
197
client_id: string;
198
redirect_uri: string;
199
200
// Optional protocol settings
201
response_type?: string;
202
scope?: string;
203
post_logout_redirect_uri?: string;
204
client_secret?: string;
205
client_authentication?: "client_secret_basic" | "client_secret_post";
206
207
// Advanced settings
208
metadata?: Partial<OidcMetadata>;
209
signingKeys?: SigningKey[];
210
extraQueryParams?: Record<string, string | number | boolean>;
211
extraHeaders?: Record<string, ExtraHeader>;
212
stateStore?: StateStore;
213
dpop?: DPoPSettings;
214
}
215
```
216
217
[Configuration](./configuration.md)
218
219
### User and Token Information
220
221
User profile and token data structures with comprehensive claims support.
222
223
```typescript { .api }
224
class User {
225
constructor(args: {
226
id_token?: string;
227
session_state?: string;
228
access_token?: string;
229
refresh_token?: string;
230
token_type?: string;
231
scope?: string;
232
profile?: UserProfile;
233
expires_at?: number;
234
state?: unknown;
235
});
236
237
readonly id_token?: string;
238
readonly session_state?: string;
239
readonly access_token?: string;
240
readonly refresh_token?: string;
241
readonly token_type?: string;
242
readonly scope?: string;
243
readonly profile?: UserProfile;
244
readonly expires_at?: number;
245
readonly expires_in?: number;
246
readonly expired: boolean;
247
readonly scopes: string[];
248
readonly state?: unknown;
249
250
toStorageString(): string;
251
}
252
253
interface UserProfile extends IdTokenClaims {
254
sub: string;
255
name?: string;
256
given_name?: string;
257
family_name?: string;
258
middle_name?: string;
259
nickname?: string;
260
preferred_username?: string;
261
profile?: string;
262
picture?: string;
263
website?: string;
264
email?: string;
265
email_verified?: boolean;
266
gender?: string;
267
birthdate?: string;
268
zoneinfo?: string;
269
locale?: string;
270
phone_number?: string;
271
phone_number_verified?: boolean;
272
address?: OidcAddressClaim;
273
updated_at?: number;
274
}
275
```
276
277
[User and Token Information](./user-tokens.md)
278
279
### Event System
280
281
Comprehensive event system for user state changes, token expiration, and error handling.
282
283
```typescript { .api }
284
class UserManagerEvents {
285
// Event registration
286
addUserLoaded(callback: UserLoadedCallback): void;
287
addUserUnloaded(callback: UserUnloadedCallback): void;
288
addUserSignedIn(callback: UserSignedInCallback): void;
289
addUserSignedOut(callback: UserSignedOutCallback): void;
290
addUserSessionChanged(callback: UserSessionChangedCallback): void;
291
addSilentRenewError(callback: SilentRenewErrorCallback): void;
292
293
// Event removal
294
removeUserLoaded(callback: UserLoadedCallback): void;
295
removeUserUnloaded(callback: UserUnloadedCallback): void;
296
removeUserSignedIn(callback: UserSignedInCallback): void;
297
removeUserSignedOut(callback: UserSignedOutCallback): void;
298
removeUserSessionChanged(callback: UserSessionChangedCallback): void;
299
removeSilentRenewError(callback: SilentRenewErrorCallback): void;
300
}
301
302
class AccessTokenEvents {
303
addAccessTokenExpiring(callback: AccessTokenCallback): void;
304
addAccessTokenExpired(callback: AccessTokenCallback): void;
305
removeAccessTokenExpiring(callback: AccessTokenCallback): void;
306
removeAccessTokenExpired(callback: AccessTokenCallback): void;
307
}
308
309
// Event callback types
310
type UserLoadedCallback = (user: User) => Promise<void> | void;
311
type UserUnloadedCallback = () => Promise<void> | void;
312
type UserSignedInCallback = () => Promise<void> | void;
313
type UserSignedOutCallback = () => Promise<void> | void;
314
type UserSessionChangedCallback = () => Promise<void> | void;
315
type SilentRenewErrorCallback = (error: Error) => Promise<void> | void;
316
type AccessTokenCallback = (...ev: unknown[]) => Promise<void> | void;
317
```
318
319
[Event System](./events.md)
320
321
### Storage and State Management
322
323
Flexible storage options for user data and request state with built-in and custom implementations.
324
325
```typescript { .api }
326
interface StateStore {
327
set(key: string, value: string): Promise<void>;
328
get(key: string): Promise<string | null>;
329
remove(key: string): Promise<string | null>;
330
getAllKeys(): Promise<string[]>;
331
}
332
333
class WebStorageStateStore implements StateStore {
334
constructor(args?: { store?: Storage; prefix?: string });
335
set(key: string, value: string): Promise<void>;
336
get(key: string): Promise<string | null>;
337
remove(key: string): Promise<string | null>;
338
getAllKeys(): Promise<string[]>;
339
}
340
341
class InMemoryWebStorage implements StateStore {
342
setItem(key: string, value: string): void;
343
getItem(key: string): string | null;
344
removeItem(key: string): void;
345
key(index: number): string | null;
346
readonly length: number;
347
}
348
349
// DPoP support
350
interface DPoPStore {
351
set(key: string, value: DPoPState): Promise<void>;
352
get(key: string): Promise<DPoPState>;
353
remove(key: string): Promise<DPoPState>;
354
getAllKeys(): Promise<string[]>;
355
}
356
357
class IndexedDbDPoPStore implements DPoPStore {
358
constructor(args?: { dbName?: string; tableName?: string });
359
set(key: string, value: DPoPState): Promise<void>;
360
get(key: string): Promise<DPoPState>;
361
remove(key: string): Promise<DPoPState>;
362
getAllKeys(): Promise<string[]>;
363
}
364
```
365
366
[Storage and State Management](./storage.md)
367
368
### Error Handling
369
370
Comprehensive error types for authentication failures, timeouts, and protocol errors.
371
372
```typescript { .api }
373
class ErrorResponse extends Error {
374
constructor(args: {
375
error: string;
376
error_description?: string;
377
error_uri?: string;
378
state?: string;
379
session_state?: string;
380
});
381
382
readonly error: string;
383
readonly error_description?: string;
384
readonly error_uri?: string;
385
readonly state?: string;
386
readonly session_state?: string;
387
}
388
389
class ErrorTimeout extends Error {
390
constructor(message?: string);
391
}
392
```
393
394
[Error Handling](./errors.md)
395
396
### Utilities and Logging
397
398
Utility functions for cryptography, JWT handling, URL manipulation, and configurable logging.
399
400
```typescript { .api }
401
// Logging
402
class Logger {
403
constructor(name: string);
404
debug(message: string, ...args: unknown[]): void;
405
info(message: string, ...args: unknown[]): void;
406
warn(message: string, ...args: unknown[]): void;
407
error(message: string, ...args: unknown[]): void;
408
create(name: string): Logger;
409
}
410
411
class Log {
412
static NONE: number;
413
static ERROR: number;
414
static WARN: number;
415
static INFO: number;
416
static DEBUG: number;
417
418
static level: number;
419
static logger: Console;
420
}
421
422
// Utility functions
423
class CryptoUtils {
424
static generateUUIDv4(): string;
425
static generateCodeVerifier(): string;
426
static generateCodeChallenge(codeVerifier: string): Promise<string>;
427
static generateBasicAuth(client_id: string, client_secret: string): string;
428
}
429
430
class JwtUtils {
431
static decode(token: string): JwtClaims;
432
}
433
434
class UrlUtils {
435
static readParams(url: string, responseMode?: "query" | "fragment"): URLSearchParams;
436
}
437
438
// Version information
439
const Version: string;
440
```
441
442
[Utilities and Logging](./utilities.md)