0
# Authentication and Session Management
1
2
Core authentication functionality providing login, logout, token management, and session handling for web applications integrated with Keycloak.
3
4
## Capabilities
5
6
### Keycloak Constructor
7
8
Creates a new Keycloak instance with server configuration.
9
10
```javascript { .api }
11
/**
12
* Creates a new Keycloak authentication client
13
* @param config - Configuration object with server details
14
*/
15
constructor(config: KeycloakConfig);
16
17
interface KeycloakConfig {
18
/** Base URL of the Keycloak server */
19
url: string;
20
/** Name of the realm */
21
realm: string;
22
/** Client ID of the application */
23
clientId: string;
24
}
25
```
26
27
**Usage Example:**
28
29
```javascript
30
import Keycloak from "keycloak-js";
31
32
const keycloak = new Keycloak({
33
url: "https://auth.mycompany.com",
34
realm: "mycompany-realm",
35
clientId: "web-app"
36
});
37
```
38
39
### Initialize Authentication
40
41
Initializes the Keycloak instance and determines authentication state.
42
43
```javascript { .api }
44
/**
45
* Initializes Keycloak instance and checks authentication state
46
* @param options - Initialization options
47
* @returns Promise resolving to true if user is authenticated
48
*/
49
init(options?: KeycloakInitOptions): Promise<boolean>;
50
51
interface KeycloakInitOptions {
52
/** Action to take on load */
53
onLoad?: "login-required" | "check-sso";
54
/** Existing token for initialization */
55
token?: string;
56
/** Existing refresh token */
57
refreshToken?: string;
58
/** Existing ID token */
59
idToken?: string;
60
/** Enable login status checking via iframe */
61
checkLoginIframe?: boolean;
62
/** Interval for login status checks in seconds */
63
checkLoginIframeInterval?: number;
64
/** Response mode for authentication */
65
responseMode?: "query" | "fragment";
66
/** URI to redirect to after authentication */
67
redirectUri?: string;
68
/** URI for silent SSO checks */
69
silentCheckSsoRedirectUri?: string;
70
/** OAuth flow type */
71
flow?: "standard" | "implicit" | "hybrid";
72
/** OAuth scope parameter */
73
scope?: string;
74
/** Time difference with server in seconds */
75
timeSkew?: number;
76
/** Use nonce for security */
77
useNonce?: boolean;
78
/** Adapter type to use */
79
adapter?: "default" | "cordova" | "cordova-native";
80
/** Timeout for iframe messages in milliseconds */
81
messageReceiveTimeout?: number;
82
/** PKCE method for security */
83
pkceMethod?: "S256";
84
/** Enable debug logging */
85
enableLogging?: boolean;
86
}
87
```
88
89
**Usage Examples:**
90
91
```javascript
92
// Check SSO status without forcing login
93
const authenticated = await keycloak.init({
94
onLoad: "check-sso",
95
pkceMethod: "S256"
96
});
97
98
// Require login on page load
99
await keycloak.init({
100
onLoad: "login-required",
101
responseMode: "query",
102
scope: "openid profile email"
103
});
104
```
105
106
### User Login
107
108
Initiates the login process by redirecting to Keycloak login page.
109
110
```javascript { .api }
111
/**
112
* Initiates login process
113
* @param options - Login options
114
* @returns Promise that resolves when login redirect occurs
115
*/
116
login(options?: KeycloakLoginOptions): Promise<void>;
117
118
interface KeycloakLoginOptions {
119
/** URI to redirect to after login */
120
redirectUri?: string;
121
/** OAuth scope parameter */
122
scope?: string;
123
/** Locale for login page */
124
locale?: string;
125
/** Specific identity provider to use */
126
idpHint?: string;
127
/** Login hint for pre-filling username */
128
loginHint?: string;
129
/** Action to perform (e.g., 'register') */
130
action?: string;
131
}
132
```
133
134
### User Registration
135
136
Redirects to the Keycloak registration page.
137
138
```javascript { .api }
139
/**
140
* Initiates user registration process
141
* @param options - Registration options
142
* @returns Promise that resolves when registration redirect occurs
143
*/
144
register(options?: KeycloakRegisterOptions): Promise<void>;
145
146
interface KeycloakRegisterOptions {
147
/** URI to redirect to after registration */
148
redirectUri?: string;
149
/** Locale for registration page */
150
locale?: string;
151
}
152
```
153
154
**Usage Examples:**
155
156
```javascript
157
// Simple registration
158
await keycloak.register();
159
160
// Registration with redirect
161
await keycloak.register({
162
redirectUri: "https://myapp.com/welcome"
163
});
164
```
165
166
### Account Management
167
168
Redirects to the Keycloak account management page.
169
170
```javascript { .api }
171
/**
172
* Redirects to account management page
173
* @param options - Account management options
174
* @returns Promise that resolves when redirect occurs
175
*/
176
accountManagement(options?: KeycloakAccountOptions): Promise<void>;
177
178
interface KeycloakAccountOptions {
179
/** URI to redirect to after account management */
180
redirectUri?: string;
181
}
182
```
183
184
**Usage Example:**
185
186
```javascript
187
// Open account management
188
await keycloak.accountManagement({
189
redirectUri: "https://myapp.com/profile-updated"
190
});
191
```
192
193
194
**Usage Examples:**
195
196
```javascript
197
// Simple login
198
await keycloak.login();
199
200
// Login with custom redirect
201
await keycloak.login({
202
redirectUri: "https://myapp.com/dashboard"
203
});
204
205
// Login with specific locale and scope
206
await keycloak.login({
207
locale: "en",
208
scope: "openid profile email custom-scope",
209
loginHint: "user@example.com"
210
});
211
212
// Login with identity provider hint
213
await keycloak.login({
214
idpHint: "google"
215
});
216
```
217
218
### User Logout
219
220
Logs out the user and optionally redirects to a specified URL.
221
222
```javascript { .api }
223
/**
224
* Logs out the user
225
* @param options - Logout options
226
* @returns Promise that resolves when logout redirect occurs
227
*/
228
logout(options?: KeycloakLogoutOptions): Promise<void>;
229
230
interface KeycloakLogoutOptions {
231
/** URI to redirect to after logout */
232
redirectUri?: string;
233
}
234
```
235
236
**Usage Examples:**
237
238
```javascript
239
// Simple logout
240
await keycloak.logout();
241
242
// Logout with redirect
243
await keycloak.logout({
244
redirectUri: "https://myapp.com/goodbye"
245
});
246
```
247
248
### Token Management
249
250
Updates access token if it expires within specified time.
251
252
```javascript { .api }
253
/**
254
* Updates token if it expires within specified time
255
* @param minValidity - Minimum token validity time in seconds (default: 5)
256
* @returns Promise resolving to true if token was refreshed
257
*/
258
updateToken(minValidity?: number): Promise<boolean>;
259
```
260
261
**Usage Examples:**
262
263
```javascript
264
// Update token if expires within 5 seconds
265
const refreshed = await keycloak.updateToken();
266
267
// Update token if expires within 30 seconds
268
const refreshed = await keycloak.updateToken(30);
269
270
// Use in API requests
271
async function makeApiCall() {
272
try {
273
await keycloak.updateToken(5);
274
const response = await fetch("/api/data", {
275
headers: {
276
Authorization: `Bearer ${keycloak.token}`
277
}
278
});
279
return response.json();
280
} catch (error) {
281
// Token refresh failed, redirect to login
282
await keycloak.login();
283
}
284
}
285
```
286
287
### Token Expiry Check
288
289
Checks if the access token is expired.
290
291
```javascript { .api }
292
/**
293
* Checks if access token is expired
294
* @param minValidity - Minimum validity time in seconds (default: 0)
295
* @returns True if token is expired
296
*/
297
isTokenExpired(minValidity?: number): boolean;
298
```
299
300
**Usage Example:**
301
302
```javascript
303
if (keycloak.isTokenExpired(30)) {
304
console.log("Token expires within 30 seconds");
305
await keycloak.updateToken(30);
306
}
307
```
308
309
### Clear Tokens
310
311
Clears all tokens from the Keycloak instance.
312
313
```javascript { .api }
314
/**
315
* Clears all tokens from Keycloak instance
316
*/
317
clearToken(): void;
318
```
319
320
**Usage Example:**
321
322
```javascript
323
// Clear tokens on logout
324
keycloak.clearToken();
325
console.log("Tokens cleared", !keycloak.token);
326
```
327
328
### User Information
329
330
Loads detailed user information from the Keycloak server.
331
332
```javascript { .api }
333
/**
334
* Loads user profile information from Keycloak server
335
* @returns Promise resolving to user profile object
336
*/
337
loadUserInfo(): Promise<any>;
338
339
/**
340
* Loads user profile with full user details
341
* @returns Promise resolving to KeycloakProfile object
342
*/
343
loadUserProfile(): Promise<KeycloakProfile>;
344
345
interface KeycloakProfile {
346
id?: string;
347
username?: string;
348
email?: string;
349
firstName?: string;
350
lastName?: string;
351
enabled?: boolean;
352
emailVerified?: boolean;
353
totp?: boolean;
354
createdTimestamp?: number;
355
attributes?: { [key: string]: string[] };
356
}
357
```
358
359
**Usage Examples:**
360
361
```javascript
362
if (keycloak.authenticated) {
363
// Load user info (OpenID Connect userinfo endpoint)
364
const userInfo = await keycloak.loadUserInfo();
365
console.log("User email:", userInfo.email);
366
console.log("User name:", userInfo.name);
367
368
// Load full user profile (Keycloak-specific)
369
const profile = await keycloak.loadUserProfile();
370
console.log("Username:", profile.username);
371
console.log("Created:", new Date(profile.createdTimestamp));
372
}
373
```
374
375
## Authentication Properties
376
377
### Authentication Status
378
379
```javascript { .api }
380
/**
381
* Whether user is currently authenticated
382
*/
383
authenticated?: boolean;
384
```
385
386
### Token Properties
387
388
```javascript { .api }
389
/**
390
* Current access token
391
*/
392
token?: string;
393
394
/**
395
* Current refresh token for obtaining new access tokens
396
*/
397
refreshToken?: string;
398
399
/**
400
* Current ID token containing user identity information
401
*/
402
idToken?: string;
403
404
/**
405
* Parsed access token payload as JavaScript object
406
*/
407
tokenParsed?: KeycloakTokenParsed;
408
409
/**
410
* Parsed ID token payload as JavaScript object
411
*/
412
idTokenParsed?: KeycloakTokenParsed;
413
414
/**
415
* User subject (ID) from token
416
*/
417
subject?: string;
418
419
/**
420
* Realm-level roles assigned to user
421
*/
422
realmAccess?: KeycloakRoles;
423
424
/**
425
* Resource-specific roles assigned to user
426
*/
427
resourceAccess?: KeycloakResourceAccess;
428
429
/**
430
* Time difference with server in seconds
431
*/
432
timeSkew?: number;
433
434
/**
435
* Current response mode used
436
*/
437
responseMode?: string;
438
439
/**
440
* Current OAuth flow type
441
*/
442
flow?: string;
443
444
/**
445
* Adapter type being used
446
*/
447
adapter?: string;
448
449
/**
450
* OAuth response type
451
*/
452
responseType?: string;
453
454
interface KeycloakTokenParsed {
455
exp?: number;
456
iat?: number;
457
auth_time?: number;
458
jti?: string;
459
iss?: string;
460
aud?: string | string[];
461
sub?: string;
462
typ?: string;
463
azp?: string;
464
session_state?: string;
465
realm_access?: KeycloakRoles;
466
resource_access?: KeycloakResourceAccess;
467
[key: string]: any;
468
}
469
470
interface KeycloakRoles {
471
roles: string[];
472
}
473
474
interface KeycloakResourceAccess {
475
[key: string]: KeycloakRoles;
476
}
477
```
478
479
**Usage Examples:**
480
481
```javascript
482
if (keycloak.authenticated) {
483
console.log("Access token:", keycloak.token);
484
console.log("User ID:", keycloak.subject);
485
console.log("Token expires at:", new Date(keycloak.tokenParsed.exp * 1000));
486
console.log("Realm roles:", keycloak.realmAccess?.roles);
487
console.log("Resource roles:", keycloak.resourceAccess);
488
}
489
```
490
491
## Event Callbacks
492
493
### Authentication Events
494
495
```javascript { .api }
496
/**
497
* Called when Keycloak is ready and authentication state is determined
498
*/
499
onReady?: (authenticated: boolean) => void;
500
501
/**
502
* Called when user is successfully authenticated
503
*/
504
onAuthSuccess?: () => void;
505
506
/**
507
* Called when authentication error occurs
508
*/
509
onAuthError?: (errorData: KeycloakError) => void;
510
511
/**
512
* Called when token is successfully refreshed
513
*/
514
onAuthRefreshSuccess?: () => void;
515
516
/**
517
* Called when token refresh fails
518
*/
519
onAuthRefreshError?: () => void;
520
521
/**
522
* Called when user is logged out
523
*/
524
onAuthLogout?: () => void;
525
526
/**
527
* Called when access token expires
528
*/
529
onTokenExpired?: () => void;
530
531
interface KeycloakError {
532
error: string;
533
error_description?: string;
534
}
535
```
536
537
**Usage Examples:**
538
539
```javascript
540
// Set up event handlers
541
keycloak.onReady = (authenticated) => {
542
console.log("Keycloak ready, authenticated:", authenticated);
543
if (authenticated) {
544
loadUserDashboard();
545
} else {
546
showLoginPage();
547
}
548
};
549
550
keycloak.onAuthSuccess = () => {
551
console.log("User authenticated successfully");
552
loadUserDashboard();
553
};
554
555
keycloak.onAuthError = (errorData) => {
556
console.error("Authentication failed:", errorData.error);
557
showErrorMessage(errorData.error_description || "Login failed");
558
};
559
560
keycloak.onAuthRefreshSuccess = () => {
561
console.log("Token refreshed successfully");
562
};
563
564
keycloak.onAuthRefreshError = () => {
565
console.error("Token refresh failed, redirecting to login");
566
keycloak.login();
567
};
568
569
keycloak.onAuthLogout = () => {
570
console.log("User logged out");
571
redirectToHomePage();
572
};
573
574
keycloak.onTokenExpired = () => {
575
console.log("Token expired, refreshing...");
576
keycloak.updateToken();
577
};
578
```
579
580
### Role Checking
581
582
Methods for checking user roles and permissions.
583
584
```javascript { .api }
585
/**
586
* Checks if user has a specific realm role
587
* @param role - Role name to check
588
* @returns True if user has the role
589
*/
590
hasRealmRole(role: string): boolean;
591
592
/**
593
* Checks if user has a specific resource role
594
* @param role - Role name to check
595
* @param resource - Resource name (defaults to clientId)
596
* @returns True if user has the role for the resource
597
*/
598
hasResourceRole(role: string, resource?: string): boolean;
599
```
600
601
**Usage Examples:**
602
603
```javascript
604
// Check realm roles
605
if (keycloak.hasRealmRole('admin')) {
606
console.log('User is an admin');
607
showAdminPanel();
608
}
609
610
if (keycloak.hasRealmRole('user')) {
611
console.log('User has basic user role');
612
}
613
614
// Check resource-specific roles
615
if (keycloak.hasResourceRole('manager', 'hr-app')) {
616
console.log('User is a manager in HR app');
617
enableManagerFeatures();
618
}
619
620
// Check role for current client
621
if (keycloak.hasResourceRole('premium-user')) {
622
console.log('User has premium access');
623
enablePremiumFeatures();
624
}
625
```
626
627
### URL Generation
628
629
Methods for generating Keycloak URLs for various operations.
630
631
```javascript { .api }
632
/**
633
* Creates a login URL
634
* @param options - Login options
635
* @returns Login URL string
636
*/
637
createLoginUrl(options?: KeycloakLoginOptions): string;
638
639
/**
640
* Creates a logout URL
641
* @param options - Logout options
642
* @returns Logout URL string
643
*/
644
createLogoutUrl(options?: KeycloakLogoutOptions): string;
645
646
/**
647
* Creates a registration URL
648
* @param options - Registration options
649
* @returns Registration URL string
650
*/
651
createRegisterUrl(options?: KeycloakRegisterOptions): string;
652
653
/**
654
* Creates an account management URL
655
* @param options - Account options
656
* @returns Account management URL string
657
*/
658
createAccountUrl(options?: KeycloakAccountOptions): string;
659
```
660
661
**Usage Examples:**
662
663
```javascript
664
// Generate URLs for custom navigation
665
const loginUrl = keycloak.createLoginUrl({
666
redirectUri: 'https://myapp.com/dashboard',
667
locale: 'en'
668
});
669
670
const logoutUrl = keycloak.createLogoutUrl({
671
redirectUri: 'https://myapp.com/goodbye'
672
});
673
674
const registerUrl = keycloak.createRegisterUrl({
675
redirectUri: 'https://myapp.com/welcome'
676
});
677
678
const accountUrl = keycloak.createAccountUrl();
679
680
// Use URLs in custom UI
681
document.getElementById('login-link').href = loginUrl;
682
document.getElementById('logout-link').href = logoutUrl;
683
document.getElementById('register-link').href = registerUrl;
684
document.getElementById('account-link').href = accountUrl;
685
```
686
687
## Error Handling
688
689
Common error scenarios and handling patterns:
690
691
```javascript
692
// Initialize with error handling
693
try {
694
const authenticated = await keycloak.init({
695
onLoad: "check-sso"
696
});
697
698
if (authenticated) {
699
// User is logged in
700
setupAuthenticatedApp();
701
} else {
702
// User is not logged in
703
setupGuestApp();
704
}
705
} catch (error) {
706
console.error("Keycloak initialization failed:", error);
707
showErrorMessage("Authentication service unavailable");
708
}
709
710
// Token refresh with fallback
711
async function secureApiCall() {
712
try {
713
await keycloak.updateToken(5);
714
return await fetch("/api/secure-data", {
715
headers: {
716
Authorization: `Bearer ${keycloak.token}`
717
}
718
});
719
} catch (error) {
720
if (error.message.includes("token")) {
721
// Token refresh failed, redirect to login
722
await keycloak.login();
723
} else {
724
throw error;
725
}
726
}
727
}
728
```