0
# User Management
1
2
High-level user authentication and session management with support for multiple authentication flows, automatic token renewal, and comprehensive event handling.
3
4
## Capabilities
5
6
### UserManager Class
7
8
The primary class for managing user authentication with the OIDC/OAuth2 provider.
9
10
```typescript { .api }
11
/**
12
* Provides a higher level API for signing a user in, signing out, managing user claims,
13
* and managing access tokens from the identity provider
14
*/
15
class UserManager {
16
constructor(settings: UserManagerSettings, redirectNavigator?: INavigator, popupNavigator?: INavigator, iframeNavigator?: INavigator);
17
18
/** Get the settings used to configure the UserManager */
19
readonly settings: UserManagerSettingsStore;
20
/** Get object used to register for events raised by the UserManager */
21
readonly events: UserManagerEvents;
22
/** Get object used to access the metadata configuration of the identity provider */
23
readonly metadataService: MetadataService;
24
}
25
```
26
27
### Authentication Flows
28
29
#### Redirect Flow
30
31
Standard browser redirect-based authentication flow.
32
33
```typescript { .api }
34
/**
35
* Trigger a redirect of the current window to the authorization endpoint
36
* @param args - Optional signin arguments
37
* @throws Error in cases of wrong authentication
38
*/
39
signinRedirect(args?: SigninRedirectArgs): Promise<void>;
40
41
/**
42
* Process the response (callback) from the authorization endpoint
43
* @param url - The callback URL (defaults to current location)
44
* @returns Promise containing the authenticated User
45
*/
46
signinRedirectCallback(url?: string): Promise<User>;
47
48
interface SigninRedirectArgs extends RedirectParams, ExtraSigninRequestArgs {
49
// Redirect-specific parameters
50
}
51
52
interface RedirectParams {
53
/** The method used to redirect ("replace" | "assign") */
54
redirectMethod?: "replace" | "assign";
55
/** The target window being redirected ("top" | "self") */
56
redirectTarget?: "top" | "self";
57
}
58
```
59
60
**Usage Example:**
61
62
```typescript
63
import { UserManager } from "oidc-client-ts";
64
65
const userManager = new UserManager({
66
authority: "https://demo.identityserver.io",
67
client_id: "interactive.public",
68
redirect_uri: "http://localhost:5000/callback",
69
response_type: "code",
70
scope: "openid profile email api",
71
});
72
73
// Initiate sign-in
74
await userManager.signinRedirect();
75
76
// In your callback page/component
77
try {
78
const user = await userManager.signinRedirectCallback();
79
console.log("User signed in:", user.profile);
80
} catch (error) {
81
console.error("Sign-in failed:", error);
82
}
83
```
84
85
#### Popup Flow
86
87
Authentication using a popup window for better user experience.
88
89
```typescript { .api }
90
/**
91
* Trigger a popup window to navigate to the authorization endpoint
92
* @param args - Optional popup signin arguments
93
* @returns Promise containing the authenticated User
94
*/
95
signinPopup(args?: SigninPopupArgs): Promise<User>;
96
97
/**
98
* Process the callback from the authorization endpoint via popup
99
* @param url - The callback URL (defaults to current location)
100
*/
101
signinPopupCallback(url?: string): Promise<void>;
102
103
interface SigninPopupArgs extends PopupWindowParams, ExtraSigninRequestArgs {
104
// Popup-specific parameters
105
}
106
107
interface PopupWindowParams {
108
/** Features parameter for window.open */
109
popupWindowFeatures?: PopupWindowFeatures;
110
/** Target parameter for window.open */
111
popupWindowTarget?: string;
112
}
113
114
interface PopupWindowFeatures {
115
location?: boolean;
116
toolbar?: boolean;
117
height?: number;
118
width?: number;
119
left?: number;
120
top?: number;
121
closePopupWindowAfterInSeconds?: number;
122
}
123
```
124
125
**Usage Example:**
126
127
```typescript
128
// Sign in with popup
129
try {
130
const user = await userManager.signinPopup({
131
popupWindowFeatures: {
132
height: 600,
133
width: 400,
134
location: false,
135
toolbar: false,
136
},
137
});
138
console.log("User signed in:", user.profile);
139
} catch (error) {
140
console.error("Popup sign-in failed:", error);
141
}
142
```
143
144
#### Silent Flow
145
146
Background authentication using hidden iframe for token renewal.
147
148
```typescript { .api }
149
/**
150
* Trigger a silent request (via iframe) to the authorization endpoint
151
* @param args - Optional silent signin arguments
152
* @returns Promise containing the authenticated User
153
*/
154
signinSilent(args?: SigninSilentArgs): Promise<User>;
155
156
/**
157
* Process the callback from the authorization endpoint via iframe
158
* @param url - The callback URL (defaults to current location)
159
* @returns Promise containing the authenticated User
160
*/
161
signinSilentCallback(url?: string): Promise<User>;
162
163
interface SigninSilentArgs extends IFrameWindowParams, ExtraSigninRequestArgs {
164
// Silent-specific parameters
165
}
166
167
interface IFrameWindowParams {
168
/** Target origin for postMessage communication */
169
iframeNotifyParentOrigin?: string;
170
/** Script origin to validate during message callback */
171
iframeScriptOrigin?: string;
172
}
173
```
174
175
#### Resource Owner Password Credentials Flow
176
177
Direct username/password authentication (not recommended for browser applications).
178
179
```typescript { .api }
180
/**
181
* Process resource owner password credentials (ROPC) grant
182
* @param args - Username and password credentials
183
* @returns Promise containing the authenticated User
184
*/
185
signinResourceOwnerCredentials(args: SigninResourceOwnerCredentialsArgs): Promise<User>;
186
187
interface SigninResourceOwnerCredentialsArgs {
188
username: string;
189
password: string;
190
skipUserInfo?: boolean;
191
extraTokenParams?: Record<string, unknown>;
192
}
193
```
194
195
#### Universal Callback Methods
196
197
Recommended universal callback methods that automatically detect and process any type of authentication or signout callback.
198
199
```typescript { .api }
200
/**
201
* Process any signin response (callback) from the authorization endpoint.
202
* Automatically detects the request type and dispatches to appropriate callback handler.
203
* @param url - The callback URL (defaults to current location)
204
* @returns Promise containing the authenticated User or undefined
205
*/
206
signinCallback(url?: string): Promise<User | undefined>;
207
208
/**
209
* Process any signout response (callback) from the end session endpoint.
210
* Automatically detects the request type and dispatches to appropriate callback handler.
211
* @param url - The callback URL (defaults to current location)
212
* @param keepOpen - Whether to keep popup windows open (defaults to false)
213
* @returns Promise containing the signout response or undefined
214
*/
215
signoutCallback(url?: string, keepOpen?: boolean): Promise<SignoutResponse | undefined>;
216
```
217
218
### Sign Out Flows
219
220
#### Redirect Sign Out
221
222
```typescript { .api }
223
/**
224
* Trigger a redirect of the current window to the end session endpoint
225
* @param args - Optional signout arguments
226
*/
227
signoutRedirect(args?: SignoutRedirectArgs): Promise<void>;
228
229
/**
230
* Process the callback from the end session endpoint
231
* @param url - The callback URL (defaults to current location)
232
* @returns Promise containing the signout response
233
*/
234
signoutRedirectCallback(url?: string): Promise<SignoutResponse>;
235
236
interface SignoutRedirectArgs extends RedirectParams, ExtraSignoutRequestArgs {
237
// Redirect signout parameters
238
}
239
```
240
241
#### Popup Sign Out
242
243
```typescript { .api }
244
/**
245
* Trigger a popup window to navigate to the end session endpoint
246
* @param args - Optional popup signout arguments
247
*/
248
signoutPopup(args?: SignoutPopupArgs): Promise<void>;
249
250
/**
251
* Process the callback from the end session endpoint via popup
252
* @param url - The callback URL (defaults to current location)
253
*/
254
signoutPopupCallback(url?: string): Promise<void>;
255
256
interface SignoutPopupArgs extends PopupWindowParams, ExtraSignoutRequestArgs {
257
// Popup signout parameters
258
}
259
```
260
261
#### Silent Sign Out
262
263
```typescript { .api }
264
/**
265
* Trigger a silent signout via iframe
266
* @param args - Optional silent signout arguments
267
*/
268
signoutSilent(args?: SignoutSilentArgs): Promise<void>;
269
270
interface SignoutSilentArgs extends IFrameWindowParams, ExtraSignoutRequestArgs {
271
// Silent signout parameters
272
}
273
```
274
275
### User Operations
276
277
```typescript { .api }
278
/**
279
* Load the User object for the currently authenticated user
280
* @param raiseEvent - Whether to raise the UserLoaded event (default: false)
281
* @returns Promise containing the User or null if not authenticated
282
*/
283
getUser(raiseEvent?: boolean): Promise<User | null>;
284
285
/**
286
* Remove from storage the currently authenticated user
287
*/
288
removeUser(): Promise<void>;
289
290
/**
291
* Store a User object in the configured storage
292
* @param user - The User object to store
293
*/
294
storeUser(user: User): Promise<void>;
295
```
296
297
### Token Management
298
299
```typescript { .api }
300
/**
301
* Start the automatic silent renew process
302
*/
303
startSilentRenew(): void;
304
305
/**
306
* Stop the automatic silent renew process
307
*/
308
stopSilentRenew(): void;
309
310
/**
311
* Revoke the user's tokens at the authorization server
312
* @param types - Token types to revoke (defaults to configured types)
313
*/
314
revokeTokens(types?: RevokeTokensTypes): Promise<void>;
315
316
type RevokeTokensTypes = ("access_token" | "refresh_token")[];
317
```
318
319
### Session Monitoring
320
321
```typescript { .api }
322
/**
323
* Query the user's session status at the identity provider
324
* @param args - Optional query arguments
325
* @returns Promise containing the session status
326
*/
327
querySessionStatus(args?: QuerySessionStatusArgs): Promise<SessionStatus>;
328
329
interface QuerySessionStatusArgs extends IFrameWindowParams, ExtraSigninRequestArgs {
330
// Session query parameters
331
}
332
333
interface SessionStatus {
334
/** Opaque session state used to validate if session changed */
335
session_state: string;
336
/** Subject identifier */
337
sub?: string;
338
}
339
```
340
341
### Common Request Arguments
342
343
```typescript { .api }
344
interface ExtraSigninRequestArgs {
345
/** Random value to maintain state between request and callback */
346
nonce?: string;
347
/** Additional query parameters for the authorization request */
348
extraQueryParams?: Record<string, string | number | boolean>;
349
/** Additional parameters for the token request */
350
extraTokenParams?: Record<string, unknown>;
351
/** Custom state data to round-trip */
352
state?: unknown;
353
/** Override the redirect URI */
354
redirect_uri?: string;
355
/** Space-delimited list of requested scopes */
356
scope?: string;
357
/** Prompt parameter (none, login, consent, select_account) */
358
prompt?: string;
359
/** Requested Authentication Context Class Reference values */
360
acr_values?: string;
361
/** Hint about the user for whom authentication is requested */
362
login_hint?: string;
363
/** Maximum authentication age in seconds */
364
max_age?: number;
365
/** Preferred languages for the authentication UI */
366
ui_locales?: string;
367
/** Resource indicators for the requested access token */
368
resource?: string | string[];
369
/** Custom URL state parameter */
370
url_state?: boolean;
371
}
372
373
interface ExtraSignoutRequestArgs {
374
/** Additional query parameters for the end session request */
375
extraQueryParams?: Record<string, string | number | boolean>;
376
/** Custom state data to round-trip */
377
state?: unknown;
378
/** ID token hint for the signout request */
379
id_token_hint?: string;
380
/** Override the post logout redirect URI */
381
post_logout_redirect_uri?: string;
382
/** Custom URL state parameter */
383
url_state?: boolean;
384
}
385
```
386
387
**Complete Usage Example:**
388
389
```typescript
390
import { UserManager, User } from "oidc-client-ts";
391
392
const userManager = new UserManager({
393
authority: "https://demo.identityserver.io",
394
client_id: "interactive.public",
395
redirect_uri: "http://localhost:5000/callback",
396
post_logout_redirect_uri: "http://localhost:5000",
397
response_type: "code",
398
scope: "openid profile email api",
399
automaticSilentRenew: true,
400
silent_redirect_uri: "http://localhost:5000/silent-callback.html",
401
});
402
403
// Set up event handling
404
userManager.events.addUserLoaded((user: User) => {
405
console.log("User loaded:", user.profile);
406
});
407
408
userManager.events.addUserSignedOut(() => {
409
console.log("User signed out");
410
});
411
412
// Check if user is already authenticated
413
const user = await userManager.getUser();
414
if (user && !user.expired) {
415
console.log("User is authenticated:", user.profile);
416
} else {
417
// Start authentication flow
418
await userManager.signinRedirect();
419
}
420
421
// Sign out
422
await userManager.signoutRedirect();
423
```