This repository has been archived by the owner on Apr 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
client.ts
1089 lines (888 loc) · 27.1 KB
/
client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type {
CallbackState,
CallbackStorage,
KeycloakAdapter,
KeycloakConfig,
KeycloakEndpoints,
KeycloakError,
KeycloakFlow,
KeycloakInitOptions,
KeycloakInstance,
KeycloakLoginOptions,
KeycloakLogoutOptions,
KeycloakPkceMethod,
KeycloakProfile,
KeycloakRegisterOptions,
KeycloakResourceAccess,
KeycloakResponseMode,
KeycloakResponseType,
KeycloakRoles,
KeycloakTokenParsed,
OAuthResponse,
} from './types';
import {
decodeToken,
getRealmUrl,
isKeycloakConfig,
setupOidcEndoints,
parseCallbackParams,
} from './utils/keycloak';
import { formatQuerystringParameters } from './utils/url';
import {
createUUID,
generateCodeVerifier,
generatePkceChallenge,
} from './utils/uuid';
/**
* A client for the Keycloak authentication server.
* @see {@link https://keycloak.gitbooks.io/securing-client-applications-guide/content/topics/oidc/javascript-adapter.html|Keycloak JS adapter documentation}
*/
export class KeycloakClient implements KeycloakInstance {
authenticated?: boolean;
subject?: string;
responseMode?: KeycloakResponseMode;
responseType?: KeycloakResponseType;
flow?: KeycloakFlow;
realmAccess?: KeycloakRoles;
resourceAccess?: KeycloakResourceAccess;
token?: string;
tokenParsed?: KeycloakTokenParsed;
refreshToken?: string;
refreshTokenParsed?: KeycloakTokenParsed;
idToken?: string;
idTokenParsed?: KeycloakTokenParsed;
timeSkew?: number;
loginRequired?: boolean;
authServerUrl?: string;
realm?: string;
clientId?: string;
redirectUri?: string;
profile?: KeycloakProfile;
userInfo?: unknown; // KeycloakUserInfo;
enableLogging?: boolean;
tokenTimeoutHandle?: NodeJS.Timeout | null;
endpoints?: KeycloakEndpoints;
clientConfig: KeycloakConfig;
private adapter?: KeycloakAdapter;
private callbackStorage?: CallbackStorage;
private logInfo = this.createLogger(console.info);
private logWarn = this.createLogger(console.warn);
private refreshTokenPromise?: Promise<boolean>;
private useNonce?: boolean;
private pkceMethod?: KeycloakPkceMethod;
constructor(clientConfig: KeycloakConfig) {
this.clientConfig = clientConfig;
}
/**
* Called to initialize the adapter.
* @param initOptions Initialization options.
* @returns A promise to set functions to be invoked on success or error.
*/
public async init(initOptions: KeycloakInitOptions): Promise<boolean> {
this.authenticated = false;
if (!initOptions.adapter) {
throw new Error('Missing Keycloak adapter from initOptions');
}
this.adapter = new initOptions.adapter(
this,
this.clientConfig,
initOptions
);
this.callbackStorage = this.adapter.createCallbackStorage();
if (initOptions) {
if (typeof initOptions.useNonce !== 'undefined') {
this.useNonce = initOptions.useNonce;
}
if (initOptions.onLoad === 'login-required') {
this.loginRequired = true;
}
if (initOptions.responseMode) {
if (
initOptions.responseMode === 'query' ||
initOptions.responseMode === 'fragment'
) {
this.responseMode = initOptions.responseMode;
} else {
throw new Error('Invalid value for responseMode');
}
}
if (initOptions.flow) {
switch (initOptions.flow) {
case 'standard':
this.responseType = 'code';
break;
case 'implicit':
this.responseType = 'id_token token';
break;
case 'hybrid':
this.responseType = 'code id_token token';
break;
default:
throw new Error('Invalid value for flow');
}
this.flow = initOptions.flow;
}
if (initOptions.timeSkew != null) {
this.timeSkew = initOptions.timeSkew;
}
if (initOptions.redirectUri) {
this.redirectUri = initOptions.redirectUri;
}
if (initOptions.pkceMethod) {
if (initOptions.pkceMethod !== 'S256') {
throw new Error('Invalid value for pkceMethod');
}
this.pkceMethod = initOptions.pkceMethod;
}
if (typeof initOptions.enableLogging === 'boolean') {
this.enableLogging = initOptions.enableLogging;
} else {
this.enableLogging = false;
}
}
if (!this.responseMode) {
this.responseMode = 'fragment';
}
if (!this.responseType) {
this.responseType = 'code';
this.flow = 'standard';
}
await this.loadConfig(this.clientConfig);
// await check3pCookiesSupported(); // Not supported on RN
await this.processInit(initOptions);
// Notify onReady event handler if set
this.onReady && this.onReady(this.authenticated);
// Return authentication status
return this.authenticated;
}
/**
* Redirects to login form.
* @param options Login options.
*/
public async login(options?: KeycloakLoginOptions): Promise<void> {
return this.adapter!.login(options);
}
/**
* Redirects to logout.
* @param options Logout options.
*/
public async logout(options?: KeycloakLogoutOptions): Promise<void> {
return this.adapter!.logout(options);
}
/**
* Redirects to registration form.
* @param options The options used for the registration.
*/
public async register(options?: KeycloakRegisterOptions): Promise<void> {
return this.adapter!.register(options);
}
/**
* Redirects to the Account Management Console.
*/
public async accountManagement(): Promise<void> {
return this.adapter!.accountManagement();
}
/**
* Returns the URL to login form.
* @param options Supports same options as Keycloak#login.
*/
public createLoginUrl(options?: KeycloakLoginOptions): string {
const state = createUUID();
const nonce = createUUID();
const redirectUri = this.adapter!.redirectUri(options);
const {
scope: scopeOption,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
redirectUri: redirectUriOption,
prompt,
action,
maxAge,
loginHint,
idpHint,
locale,
...rest
} = options ?? {};
let codeVerifier;
let pkceChallenge;
if (this.pkceMethod) {
codeVerifier = generateCodeVerifier(96);
pkceChallenge = generatePkceChallenge(this.pkceMethod, codeVerifier);
}
const callbackState: CallbackState = {
state,
nonce,
pkceCodeVerifier: codeVerifier,
prompt: options?.prompt ?? undefined,
redirectUri,
};
let scope;
if (scopeOption) {
if (scopeOption.indexOf('openid') !== -1) {
scope = scopeOption;
} else {
scope = 'openid ' + scopeOption;
}
} else {
scope = 'openid';
}
const baseUrl =
action === 'register'
? this.endpoints!.register()
: this.endpoints!.authorize();
const params = new Map<string, string>();
params.set('client_id', this.clientId!);
params.set('redirect_uri', redirectUri);
params.set('state', state);
params.set('response_mode', this.responseMode!);
params.set('response_type', this.responseType!);
params.set('scope', scope);
if (this.useNonce) {
params.set('nonce', nonce);
}
if (prompt) {
params.set('prompt', prompt);
}
if (maxAge) {
params.set('max_age', `${maxAge}`);
}
if (loginHint) {
params.set('login_hint', loginHint);
}
if (idpHint) {
params.set('kc_idp_hint', idpHint);
}
if (action && action !== 'register') {
params.set('kc_action', action);
}
if (locale) {
params.set('ui_locales', locale);
}
if (this?.pkceMethod && !!pkceChallenge) {
params.set('code_challenge', pkceChallenge);
params.set('code_challenge_method', this.pkceMethod);
}
this.callbackStorage!.add(callbackState);
Object.keys(rest).forEach((key) => {
params.set(key, `${rest[key]}`);
});
return `${baseUrl}?${formatQuerystringParameters(params)}`;
}
/**
* Returns the URL to logout the user.
* @param options Logout options.
*/
public createLogoutUrl(options?: KeycloakLogoutOptions): string {
const params = new Map<string, string>();
params.set('redirect_uri', this.adapter!.redirectUri(options));
return `${this.endpoints!.logout()}?${formatQuerystringParameters(params)}`;
}
/**
* Returns the URL to registration page.
* @param options The options used for creating the registration URL.
*/
public createRegisterUrl(options: KeycloakRegisterOptions = {}): string {
return this.createLoginUrl({
...options,
action: 'register',
});
}
/**
* Returns the URL to the Account Management Console.
*/
public createAccountUrl(): string {
const realm = getRealmUrl(this.realm!, this.authServerUrl);
if (typeof realm === 'undefined') {
throw new Error('Failed to create Account URL. realm is not defined.');
}
const params = new Map<string, string>();
params.set('referrer', this.clientId!);
params.set('referrer_uri', this.adapter!.redirectUri());
return `${realm}/account?${formatQuerystringParameters(params)}`;
}
/**
* Returns true if the token has less than `minValidity` seconds left before
* it expires.
* @param minValidity If not specified, `0` is used.
*/
public isTokenExpired(minValidity?: number): boolean {
if (!this.tokenParsed || (!this.refreshToken && this.flow !== 'implicit')) {
throw 'Not authenticated';
}
if (this.timeSkew == null) {
this.logInfo(
'[KEYCLOAK] Unable to determine if token is expired as timeskew is not set'
);
return true;
}
let expiresIn =
(this.tokenParsed?.exp ?? 0) -
Math.ceil(new Date().getTime() / 1000) +
this.timeSkew;
if (minValidity) {
if (isNaN(minValidity)) {
throw 'Invalid minValidity';
}
expiresIn -= minValidity;
}
return expiresIn < 0;
}
/**
* If the token expires within `minValidity` seconds, the token is refreshed.
* If the session status iframe is enabled, the session status is also
* checked.
* @returns A promise to set functions that can be invoked if the token is
* still valid, or if the token is no longer valid.
* @example
* ```js
* keycloak.updateToken(5).then(function(refreshed) {
* if (refreshed) {
* alert('Token was successfully refreshed');
* } else {
* alert('Token is still valid');
* }
* }).catch(function() {
* alert('Failed to refresh the token, or the session has expired');
* });
*/
public async updateToken(minValidity: number = 5): Promise<boolean> {
if (!this.refreshToken) {
throw new Error('missing refreshToken');
}
if (this.refreshTokenPromise) {
return this.refreshTokenPromise;
}
this.refreshTokenPromise = new Promise<boolean>(async (resolve, reject) => {
let shouldRefreshToken: boolean = false;
if (minValidity === -1) {
shouldRefreshToken = true;
this.logInfo('[KEYCLOAK] Refreshing token: forced refresh');
} else if (!this.tokenParsed || this.isTokenExpired(minValidity)) {
shouldRefreshToken = true;
this.logInfo('[KEYCLOAK] Refreshing token: token expired');
}
if (!shouldRefreshToken) {
resolve(false);
this.refreshTokenPromise = undefined;
return;
}
const tokenUrl = this.endpoints!.token();
const params = new Map<string, string>();
params.set('client_id', this.clientId!);
params.set('grant_type', 'refresh_token');
params.set('refresh_token', this.refreshToken!);
let timeLocal = new Date().getTime();
try {
const tokenResponse = await this.adapter!.refreshTokens(
tokenUrl,
formatQuerystringParameters(params)
);
this.logInfo('[KEYCLOAK] Token refreshed');
timeLocal = (timeLocal + new Date().getTime()) / 2;
this.setToken(
tokenResponse.access_token,
tokenResponse.refresh_token,
tokenResponse.id_token,
timeLocal
);
// Notify onAuthRefreshSuccess event handler if set
this.onAuthRefreshSuccess && this.onAuthRefreshSuccess();
resolve(true);
} catch (err) {
this.logWarn('[KEYCLOAK] Failed to refresh token');
// Clear tokens
this.clearToken();
// Notify onAuthRefreshError event handler if set
this.onAuthRefreshError && this.onAuthRefreshError();
reject();
}
this.refreshTokenPromise = undefined;
});
return this.refreshTokenPromise;
}
/**
* Clears authentication state, including tokens. This can be useful if
* the application has detected the session was expired, for example if
* updating token fails. Invoking this results in Keycloak#onAuthLogout
* callback listener being invoked.
*/
public clearToken(): void {
if (this.token) {
this.setToken(null, null, null);
// Notify onAuthLogout event handler if set
this.onAuthLogout && this.onAuthLogout();
if (this.loginRequired) {
this.login();
}
}
}
/**
* Returns true if the token has the given realm role.
* @param role A realm role name.
*/
public hasRealmRole(role: string): boolean {
return !!this.realmAccess && this.realmAccess.roles?.indexOf(role) >= 0;
}
/**
* Returns true if the token has the given role for the resource.
* @param role A role name.
* @param resource If not specified, `clientId` is used.
*/
public hasResourceRole(role: string, resource?: string): boolean {
if (!this.resourceAccess) {
return false;
}
const access = this.resourceAccess[resource || this.clientId || ''];
return !!access && access.roles.indexOf(role) >= 0;
}
/**
* Loads the user's profile.
*
* @returns The current user KeycloakProfile.
*/
async loadUserProfile(): Promise<KeycloakProfile> {
const profileUrl =
getRealmUrl(this.realm!, this.authServerUrl) + '/account';
const userProfileRes = await this.adapter!.fetchUserProfile(
profileUrl,
this.token!
);
this.profile = userProfileRes;
return this.profile;
}
/**
* @private Undocumented.
*/
async loadUserInfo(): Promise<unknown> {
const userInfoUrl = this.endpoints!.userinfo();
const userInfoRes = await this.adapter!.fetchUserInfo(
userInfoUrl,
this.token!
);
this.userInfo = userInfoRes;
return this.userInfo;
}
/**
* Called when the adapter is initialized.
*/
onReady?(authenticated?: boolean): void;
/**
* Called when a user is successfully authenticated.
*/
onAuthSuccess?(): void;
/**
* Called if there was an error during authentication.
*/
onAuthError?(errorData: KeycloakError): void;
/**
* Called when the token is refreshed.
*/
onAuthRefreshSuccess?(): void;
/**
* Called if there was an error while trying to refresh the token.
*/
onAuthRefreshError?(): void;
/**
* Called if the user is logged out (will only be called if the session
* status iframe is enabled, or in Cordova mode).
*/
onAuthLogout?(): void;
/**
* Called when the access token is expired. If a refresh token is available
* the token can be refreshed with Keycloak#updateToken, or in cases where
* it's not (ie. with implicit flow) you can redirect to login screen to
* obtain a new access token.
*/
onTokenExpired?(): void;
/**
* Called when a AIA has been requested by the application.
*/
onActionUpdate?(status: 'success' | 'cancelled' | 'error'): void;
/**
* @private Undocumented.
*/
async processCallback(oauth: OAuthResponse) {
const timeLocal = new Date().getTime();
if (oauth.kc_action_status) {
this.onActionUpdate && this.onActionUpdate(oauth.kc_action_status);
}
const { code, error, prompt } = oauth;
if (error) {
if (prompt !== 'none') {
this.onAuthError &&
this.onAuthError({
error,
error_description: oauth.error_description ?? 'auth error',
});
throw new Error(oauth.error_description);
}
return;
}
if (this.flow !== 'standard' && (oauth.access_token || oauth.id_token)) {
return this.authSuccess(oauth, timeLocal, true);
}
if (this.flow !== 'implicit' && code) {
const params = new Map<string, string>();
params.set('code', code);
params.set('grant_type', 'authorization_code');
params.set('client_id', this.clientId!);
params.set('redirect_uri', oauth.redirectUri!);
if (oauth.pkceCodeVerifier) {
params.set('code_verifier', oauth.pkceCodeVerifier);
}
const tokenUrl = this.endpoints!.token();
try {
const tokenResponse = await this.adapter!.fetchTokens(
tokenUrl,
formatQuerystringParameters(params)
);
await this.authSuccess(
{
...oauth,
access_token: tokenResponse.access_token || undefined,
refresh_token: tokenResponse.refresh_token || undefined,
id_token: tokenResponse.id_token || undefined,
},
timeLocal,
this.flow === 'standard'
);
} catch (err) {
// Notify onAuthError event handler if set
this.onAuthError &&
this.onAuthError({
error: err,
error_description:
'Failed to refresh token during callback processing',
});
throw new Error(err);
}
}
}
private async authSuccess(
oauthObj: OAuthResponse,
timeLocal: number,
fulfillPromise: boolean
) {
timeLocal = (timeLocal + new Date().getTime()) / 2;
this.setToken(
oauthObj.access_token ?? null,
oauthObj.refresh_token ?? null,
oauthObj.id_token ?? null,
timeLocal
);
if (
this.useNonce &&
((this.tokenParsed && this.tokenParsed.nonce !== oauthObj.storedNonce) ||
(this.refreshTokenParsed &&
this.refreshTokenParsed.nonce !== oauthObj.storedNonce) ||
(this.idTokenParsed &&
this.idTokenParsed.nonce !== oauthObj.storedNonce))
) {
this.logInfo('[KEYCLOAK] Invalid nonce, clearing token');
this.clearToken();
throw new Error('invalid nonce, token cleared');
}
if (fulfillPromise) {
this.onAuthSuccess && this.onAuthSuccess();
}
}
/**
* @private Undocumented.
*/
parseCallback(url: string): OAuthResponse {
const oauthParsed = this.parseCallbackUrl(url);
if (!oauthParsed) {
throw new Error('Failed to parse redirect URL');
}
const oauthState = this.callbackStorage!.get(oauthParsed.state as string);
if (oauthState) {
return {
...oauthParsed,
valid: true,
redirectUri: oauthState.redirectUri,
storedNonce: oauthState.nonce,
prompt: oauthState.prompt,
pkceCodeVerifier: oauthState.pkceCodeVerifier,
};
}
return oauthParsed as OAuthResponse;
}
private async processInit(initOptions?: KeycloakInitOptions): Promise<void> {
if (initOptions) {
if (initOptions.token && initOptions.refreshToken) {
this.setToken(
initOptions.token,
initOptions.refreshToken,
initOptions.idToken ?? null
);
try {
await this.updateToken(-1);
// Notify onAuthSuccess event handler if set
this.onAuthSuccess && this.onAuthSuccess();
} catch (error) {
// Notify onAuthError event handler if set
this.onAuthError &&
this.onAuthError({
error,
error_description: 'Failed to refresh token during init',
});
if (initOptions.onLoad) {
this.onLoad(initOptions);
} else {
throw new Error('Failed to init');
}
}
// }
} else if (initOptions.onLoad) {
this.onLoad(initOptions);
}
}
}
private async onLoad(initOptions: KeycloakInitOptions): Promise<void> {
switch (initOptions.onLoad) {
case 'login-required':
this.doLogin(initOptions, true);
break;
case 'check-sso':
break;
default:
throw new Error('Invalid value for onLoad');
}
}
private async doLogin(
initOptions: KeycloakInitOptions,
prompt?: boolean
): Promise<void> {
return this.login({
...initOptions,
prompt: !prompt ? 'none' : undefined,
});
}
private setToken(
token: string | null,
refreshToken: string | null,
idToken: string | null,
timeLocal?: number
) {
if (this.tokenTimeoutHandle) {
clearTimeout(this.tokenTimeoutHandle);
this.tokenTimeoutHandle = null;
}
if (refreshToken) {
this.refreshToken = refreshToken;
this.refreshTokenParsed = decodeToken(refreshToken);
} else {
delete this.refreshToken;
delete this.refreshTokenParsed;
}
if (idToken) {
this.idToken = idToken;
this.idTokenParsed = decodeToken(idToken);
} else {
delete this.idToken;
delete this.idTokenParsed;
}
if (token) {
this.token = token;
this.tokenParsed = decodeToken(token);
if (!this.tokenParsed) {
throw new Error('Invalid tokenParsed');
}
this.authenticated = true;
this.subject = this.tokenParsed.sub;
this.realmAccess = this.tokenParsed.realm_access;
this.resourceAccess = this.tokenParsed.resource_access;
if (timeLocal) {
this.timeSkew =
Math.floor(timeLocal / 1000) - (this.tokenParsed.iat ?? 0);
}
if (this.timeSkew != null) {
this.logInfo(
`[KEYCLOAK] Estimated time difference between browser and server is ${this.timeSkew} seconds`
);
if (this.onTokenExpired) {
const expiresIn =
((this.tokenParsed.exp ?? 0) -
new Date().getTime() / 1000 +
this.timeSkew) *
1000;
this.logInfo(
`[KEYCLOAK] Token expires in ${Math.round(expiresIn / 1000)} s`
);
if (expiresIn <= 0) {
this.onTokenExpired();
} else {
this.tokenTimeoutHandle = setTimeout(
this.onTokenExpired,
expiresIn
);
}
}
}
} else {
delete this.token;
delete this.tokenParsed;
delete this.subject;
delete this.realmAccess;
delete this.resourceAccess;
this.authenticated = false;
}
}
private createLogger(fn: (...optionalParams: unknown[]) => void): Function {
return () => {
if (this.enableLogging) {
fn.apply(console, Array.prototype.slice.call(arguments));
}
};
}
private async loadConfig(config?: KeycloakConfig | string): Promise<void> {
let configUrl;
if (!config) {
configUrl = 'keycloak.json';
} else if (typeof config === 'string') {
configUrl = config;
}
if (configUrl) {
const configJSON = await this.adapter!.fetchKeycloakConfigJSON(configUrl);
this.realm = configJSON.realm;
this.clientId = configJSON.resource;
this.endpoints = setupOidcEndoints({
realm: this.realm,
authServerUrl: this.authServerUrl,
});
return;
}
if (!isKeycloakConfig(config)) {
throw new Error('invalid configuration format');
}
if (!config.clientId) {
throw new Error('clientId missing from configuration');
}
this.clientId = config.clientId;
const oidcProvider = config.oidcProvider;
// When oidcProvider config is not supplied, use local configuration params
if (!oidcProvider) {
if (!config.realm) {
throw new Error('realm missing from configuration');
}
this.realm = config.realm;
this.authServerUrl = config.url;
this.endpoints = setupOidcEndoints({
realm: this.realm,
authServerUrl: this.authServerUrl,
});
return;
}
// When oidcProvider config is a string, load the config from the URL
if (typeof oidcProvider === 'string') {
let oidcProviderConfigUrl;
if (oidcProvider.charAt(oidcProvider.length - 1) === '/') {
oidcProviderConfigUrl =
oidcProvider + '.well-known/openid-configuration';
} else {
oidcProviderConfigUrl =
oidcProvider + '/.well-known/openid-configuration';
}
try {
const oidcProviderConfig = await this.adapter!.fetchOIDCProviderConfigJSON(
oidcProviderConfigUrl
);
this.endpoints = setupOidcEndoints({
oidcConfiguration: oidcProviderConfig,
});
return;
} catch (err) {
throw err;
}
}
// Otherwise oidcProvider is a config object and should be used
this.endpoints = setupOidcEndoints({
oidcConfiguration: oidcProvider,
});
}
private parseCallbackUrl(url: string) {
let supportedParams: string[] = [];
switch (this.flow) {
case 'standard':
supportedParams = [
'code',