@multiplatform.one/keycloak-js 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,692 @@
1
+ /*
2
+ * MIT License
3
+ *
4
+ * Copyright 2017 Brett Epps <https://github.com/eppsilon>
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
7
+ * associated documentation files (the "Software"), to deal in the Software without restriction, including
8
+ * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ * copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
10
+ * following conditions:
11
+ *
12
+ * The above copyright notice and this permission notice shall be included in all copies or substantial
13
+ * portions of the Software.
14
+ *
15
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
16
+ * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
+ * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
18
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
19
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20
+ */
21
+ export type KeycloakOnLoad = 'login-required' | 'check-sso'
22
+ export type KeycloakResponseMode = 'query' | 'fragment'
23
+ export type KeycloakResponseType = 'code' | 'id_token token' | 'code id_token token'
24
+ export type KeycloakFlow = 'standard' | 'implicit' | 'hybrid'
25
+ export type KeycloakPkceMethod = 'S256' | false
26
+
27
+ export interface KeycloakServerConfig {
28
+ /**
29
+ * URL to the Keycloak server, for example: http://keycloak-server/auth
30
+ */
31
+ url: string
32
+ /**
33
+ * Name of the realm, for example: 'myrealm'
34
+ */
35
+ realm: string
36
+ /**
37
+ * Client identifier, example: 'myapp'
38
+ */
39
+ clientId: string
40
+ }
41
+
42
+ export interface GenericOidcConfig {
43
+ /**
44
+ * Client identifier, example: 'myapp'
45
+ */
46
+ clientId: string
47
+ /** Generic OpenID Connect configuration, can be a URL to the discovery metadata endpoint, or the metadata itself. */
48
+ oidcProvider: string | OpenIdProviderMetadata
49
+ }
50
+
51
+ /**
52
+ * OpenIdProviderMetadata The OpenID version of the adapter configuration, based on the {@link https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata OpenID Connect Discovery specification}.
53
+ */
54
+ export interface OpenIdProviderMetadata {
55
+ /** URL of the OP's OAuth 2.0 Authorization Endpoint. */
56
+ authorization_endpoint: string
57
+ /** URL of the OP's OAuth 2.0 Token Endpoint. */
58
+ token_endpoint: string
59
+ /** URL of the OP's UserInfo Endpoint. */
60
+ userinfo_endpoint?: string
61
+ /** URL of an OP iframe that supports cross-origin communications for session state information with the RP Client, using the HTML5 postMessage API. */
62
+ check_session_iframe?: string
63
+ /** URL at the OP to which an RP can perform a redirect to request that the End-User be logged out at the OP. */
64
+ end_session_endpoint?: string
65
+ }
66
+
67
+ export type KeycloakConfig = KeycloakServerConfig | GenericOidcConfig
68
+
69
+ export interface Acr {
70
+ /**
71
+ * Array of values, which will be used inside ID Token `acr` claim sent inside the `claims` parameter to Keycloak server during login.
72
+ * Values should correspond to the ACR levels defined in the ACR to Loa mapping for realm or client or to the numbers (levels) inside defined
73
+ * Keycloak authentication flow. See section 5.5.1 of OIDC 1.0 specification for the details.
74
+ */
75
+ values: string[]
76
+ /**
77
+ * This parameter specifies if ACR claims is considered essential or not.
78
+ */
79
+ essential: boolean
80
+ }
81
+
82
+ export interface KeycloakInitOptions {
83
+ /**
84
+ * Adds a [cryptographic nonce](https://en.wikipedia.org/wiki/Cryptographic_nonce)
85
+ * to verify that the authentication response matches the request.
86
+ * @default true
87
+ */
88
+ useNonce?: boolean
89
+
90
+ /**
91
+ *
92
+ * Allow usage of different types of adapters or a custom adapter to make Keycloak work in different environments.
93
+ *
94
+ * The following options are supported:
95
+ * - `default` - Use default APIs that are available in browsers.
96
+ * - `cordova` - Use a WebView in Cordova.
97
+ * - `cordova-native` - Use Cordova native APIs, this is recommended over `cordova`.
98
+ *
99
+ * It's also possible to pass in a custom adapter for the environment you are running Keycloak in. In order to do so extend the `KeycloakAdapter` interface and implement the methods that are defined there.
100
+ *
101
+ * For example:
102
+ *
103
+ * ```ts
104
+ * // Implement the 'KeycloakAdapter' interface so that all required methods are guaranteed to be present.
105
+ * const MyCustomAdapter: KeycloakAdapter = {
106
+ * login(options) {
107
+ * // Write your own implementation here.
108
+ * }
109
+ *
110
+ * // The other methods go here...
111
+ * };
112
+ *
113
+ * keycloak.init({
114
+ * adapter: MyCustomAdapter,
115
+ * });
116
+ * ```
117
+ */
118
+ adapter?: 'default' | 'cordova' | 'cordova-native' | KeycloakAdapter
119
+
120
+ /**
121
+ * Specifies an action to do on load.
122
+ */
123
+ onLoad?: KeycloakOnLoad
124
+
125
+ /**
126
+ * Set an initial value for the token.
127
+ */
128
+ token?: string
129
+
130
+ /**
131
+ * Set an initial value for the refresh token.
132
+ */
133
+ refreshToken?: string
134
+
135
+ /**
136
+ * Set an initial value for the id token (only together with `token` or
137
+ * `refreshToken`).
138
+ */
139
+ idToken?: string
140
+
141
+ /**
142
+ * Set an initial value for skew between local time and Keycloak server in
143
+ * seconds (only together with `token` or `refreshToken`).
144
+ */
145
+ timeSkew?: number
146
+
147
+ /**
148
+ * Set to enable/disable monitoring login state.
149
+ * @default true
150
+ */
151
+ checkLoginIframe?: boolean
152
+
153
+ /**
154
+ * Set the interval to check login state (in seconds).
155
+ * @default 5
156
+ */
157
+ checkLoginIframeInterval?: number
158
+
159
+ /**
160
+ * Set the OpenID Connect response mode to send to Keycloak upon login.
161
+ * @default fragment After successful authentication Keycloak will redirect
162
+ * to JavaScript application with OpenID Connect parameters
163
+ * added in URL fragment. This is generally safer and
164
+ * recommended over query.
165
+ */
166
+ responseMode?: KeycloakResponseMode
167
+
168
+ /**
169
+ * Specifies a default uri to redirect to after login or logout.
170
+ * This is currently supported for adapter 'cordova-native' and 'default'
171
+ */
172
+ redirectUri?: string
173
+
174
+ /**
175
+ * Specifies an uri to redirect to after silent check-sso.
176
+ * Silent check-sso will only happen, when this redirect uri is given and
177
+ * the specified uri is available within the application.
178
+ */
179
+ silentCheckSsoRedirectUri?: string
180
+
181
+ /**
182
+ * Specifies whether the silent check-sso should fallback to "non-silent"
183
+ * check-sso when 3rd party cookies are blocked by the browser. Defaults
184
+ * to true.
185
+ */
186
+ silentCheckSsoFallback?: boolean
187
+
188
+ /**
189
+ * Set the OpenID Connect flow.
190
+ * @default standard
191
+ */
192
+ flow?: KeycloakFlow
193
+
194
+ /**
195
+ * Configures the Proof Key for Code Exchange (PKCE) method to use. This will default to 'S256'.
196
+ * Can be disabled by passing `false`.
197
+ */
198
+ pkceMethod?: KeycloakPkceMethod
199
+
200
+ /**
201
+ * Enables logging messages from Keycloak to the console.
202
+ * @default false
203
+ */
204
+ enableLogging?: boolean
205
+
206
+ /**
207
+ * Set the default scope parameter to the login endpoint. Use a space-delimited list of scopes.
208
+ * Note that the scope 'openid' will be always be added to the list of scopes by the adapter.
209
+ * Note that the default scope specified here is overwritten if the `login()` options specify scope explicitly.
210
+ */
211
+ scope?: string
212
+
213
+ /**
214
+ * Configures how long will Keycloak adapter wait for receiving messages from server in ms. This is used,
215
+ * for example, when waiting for response of 3rd party cookies check.
216
+ *
217
+ * @default 10000
218
+ */
219
+ messageReceiveTimeout?: number
220
+
221
+ /**
222
+ * When onLoad is 'login-required', sets the 'ui_locales' query param in compliance with section 3.1.2.1
223
+ * of the OIDC 1.0 specification.
224
+ */
225
+ locale?: string
226
+
227
+ /**
228
+ * HTTP method for calling the end_session endpoint. Defaults to 'GET'.
229
+ */
230
+ logoutMethod?: 'GET' | 'POST'
231
+ }
232
+
233
+ export interface KeycloakLoginOptions {
234
+ /**
235
+ * Specifies the scope parameter for the login url
236
+ * The scope 'openid' will be added to the scope if it is missing or undefined.
237
+ */
238
+ scope?: string
239
+
240
+ /**
241
+ * Specifies the uri to redirect to after login.
242
+ */
243
+ redirectUri?: string
244
+
245
+ /**
246
+ * By default the login screen is displayed if the user is not logged into
247
+ * Keycloak. To only authenticate to the application if the user is already
248
+ * logged in and not display the login page if the user is not logged in, set
249
+ * this option to `'none'`. To always require re-authentication and ignore
250
+ * SSO, set this option to `'login'`. To always prompt the user for consent,
251
+ * set this option to `'consent'`. This ensures that consent is requested,
252
+ * even if it has been given previously.
253
+ */
254
+ prompt?: 'none' | 'login' | 'consent'
255
+
256
+ /**
257
+ * If value is `'register'` then user is redirected to registration page,
258
+ * otherwise to login page.
259
+ */
260
+ action?: string
261
+
262
+ /**
263
+ * Used just if user is already authenticated. Specifies maximum time since
264
+ * the authentication of user happened. If user is already authenticated for
265
+ * longer time than `'maxAge'`, the SSO is ignored and he will need to
266
+ * authenticate again.
267
+ */
268
+ maxAge?: number
269
+
270
+ /**
271
+ * Used to pre-fill the username/email field on the login form.
272
+ */
273
+ loginHint?: string
274
+
275
+ /**
276
+ * Sets the `acr` claim of the ID token sent inside the `claims` parameter. See section 5.5.1 of the OIDC 1.0 specification.
277
+ */
278
+ acr?: Acr
279
+
280
+ /**
281
+ * Configures the 'acr_values' query param in compliance with section 3.1.2.1
282
+ * of the OIDC 1.0 specification.
283
+ * Used to tell Keycloak what level of authentication the user needs.
284
+ */
285
+ acrValues?: string
286
+
287
+ /**
288
+ * Used to tell Keycloak which IDP the user wants to authenticate with.
289
+ */
290
+ idpHint?: string
291
+
292
+ /**
293
+ * Sets the 'ui_locales' query param in compliance with section 3.1.2.1
294
+ * of the OIDC 1.0 specification.
295
+ */
296
+ locale?: string
297
+
298
+ /**
299
+ * Specifies arguments that are passed to the Cordova in-app-browser (if applicable).
300
+ * Options 'hidden' and 'location' are not affected by these arguments.
301
+ * All available options are defined at https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-inappbrowser/.
302
+ * Example of use: { zoom: "no", hardwareback: "yes" }
303
+ */
304
+ cordovaOptions?: { [optionName: string]: string }
305
+ }
306
+
307
+ export interface KeycloakLogoutOptions {
308
+ /**
309
+ * Specifies the uri to redirect to after logout.
310
+ */
311
+ redirectUri?: string
312
+
313
+ /**
314
+ * HTTP method for calling the end_session endpoint. Defaults to 'GET'.
315
+ */
316
+ logoutMethod?: 'GET' | 'POST'
317
+ }
318
+
319
+ export interface KeycloakRegisterOptions extends Omit<KeycloakLoginOptions, 'action'> { }
320
+
321
+ export interface KeycloakAccountOptions {
322
+ /**
323
+ * Specifies the uri to redirect to when redirecting back to the application.
324
+ */
325
+ redirectUri?: string
326
+ }
327
+ export interface KeycloakError {
328
+ error: string
329
+ error_description: string
330
+ }
331
+
332
+ export interface KeycloakRedirectUriOptions {
333
+ /**
334
+ * Specifies the uri to redirect to after login.
335
+ */
336
+ redirectUri?: string
337
+ }
338
+
339
+ export interface KeycloakAdapter {
340
+ login: (options?: KeycloakLoginOptions) => Promise<void>
341
+ logout: (options?: KeycloakLogoutOptions) => Promise<void>
342
+ register: (options?: KeycloakRegisterOptions) => Promise<void>
343
+ accountManagement: () => Promise<void>
344
+ redirectUri: (options?: KeycloakRedirectUriOptions) => string
345
+ }
346
+
347
+ export interface KeycloakProfile {
348
+ id?: string
349
+ username?: string
350
+ email?: string
351
+ firstName?: string
352
+ lastName?: string
353
+ enabled?: boolean
354
+ emailVerified?: boolean
355
+ totp?: boolean
356
+ createdTimestamp?: number
357
+ attributes?: Record<string, unknown>
358
+ }
359
+
360
+ export interface KeycloakTokenParsed {
361
+ iss?: string
362
+ sub?: string
363
+ aud?: string
364
+ exp?: number
365
+ iat?: number
366
+ auth_time?: number
367
+ nonce?: string
368
+ acr?: string
369
+ amr?: string
370
+ azp?: string
371
+ session_state?: string
372
+ realm_access?: KeycloakRoles
373
+ resource_access?: KeycloakResourceAccess
374
+ [key: string]: any // Add other attributes here.
375
+ }
376
+
377
+ export interface KeycloakResourceAccess {
378
+ [key: string]: KeycloakRoles
379
+ }
380
+
381
+ export interface KeycloakRoles {
382
+ roles: string[]
383
+ }
384
+
385
+ export interface KeycloakUserInfo {
386
+ sub: string
387
+ [key: string]: any
388
+ }
389
+
390
+ /**
391
+ * @deprecated Instead of importing 'KeycloakInstance' you can import 'Keycloak' directly as a type.
392
+ */
393
+ export type KeycloakInstance = Keycloak
394
+
395
+ /**
396
+ * A client for the Keycloak authentication server.
397
+ * @see {@link https://keycloak.gitbooks.io/securing-client-applications-guide/content/topics/oidc/javascript-adapter.html|Keycloak JS adapter documentation}
398
+ */
399
+ declare class Keycloak {
400
+ /**
401
+ * Creates a new Keycloak client instance.
402
+ * @param config A configuration object or path to a JSON config file.
403
+ */
404
+ constructor (config: KeycloakConfig | string)
405
+
406
+ /**
407
+ * Is true if the user is authenticated, false otherwise.
408
+ */
409
+ authenticated: boolean
410
+
411
+ /**
412
+ * The user id.
413
+ */
414
+ subject?: string
415
+
416
+ /**
417
+ * Response mode passed in init (default value is `'fragment'`).
418
+ */
419
+ responseMode: KeycloakResponseMode
420
+
421
+ /**
422
+ * Response type sent to Keycloak with login requests. This is determined
423
+ * based on the flow value used during initialization, but can be overridden
424
+ * by setting this value.
425
+ */
426
+ responseType: KeycloakResponseType
427
+
428
+ /**
429
+ * Flow passed in init.
430
+ */
431
+ flow: KeycloakFlow
432
+
433
+ /**
434
+ * The realm roles associated with the token.
435
+ */
436
+ realmAccess?: KeycloakRoles
437
+
438
+ /**
439
+ * The resource roles associated with the token.
440
+ */
441
+ resourceAccess?: KeycloakResourceAccess
442
+
443
+ /**
444
+ * The base64 encoded token that can be sent in the Authorization header in
445
+ * requests to services.
446
+ */
447
+ token?: string
448
+
449
+ /**
450
+ * The parsed token as a JavaScript object.
451
+ */
452
+ tokenParsed?: KeycloakTokenParsed
453
+
454
+ /**
455
+ * The base64 encoded refresh token that can be used to retrieve a new token.
456
+ */
457
+ refreshToken?: string
458
+
459
+ /**
460
+ * The parsed refresh token as a JavaScript object.
461
+ */
462
+ refreshTokenParsed?: KeycloakTokenParsed
463
+
464
+ /**
465
+ * The base64 encoded ID token.
466
+ */
467
+ idToken?: string
468
+
469
+ /**
470
+ * The parsed id token as a JavaScript object.
471
+ */
472
+ idTokenParsed?: KeycloakTokenParsed
473
+
474
+ /**
475
+ * The estimated time difference between the browser time and the Keycloak
476
+ * server in seconds. This value is just an estimation, but is accurate
477
+ * enough when determining if a token is expired or not.
478
+ */
479
+ timeSkew: number | null
480
+
481
+ /**
482
+ * Whether the instance has been initialized by calling `.init()`.
483
+ */
484
+ didInitialize: boolean
485
+
486
+ /**
487
+ * @private Undocumented.
488
+ */
489
+ loginRequired: boolean
490
+
491
+ /**
492
+ * @private Undocumented.
493
+ */
494
+ authServerUrl?: string
495
+
496
+ /**
497
+ * @private Undocumented.
498
+ */
499
+ realm?: string
500
+
501
+ /**
502
+ * @private Undocumented.
503
+ */
504
+ clientId?: string
505
+
506
+ /**
507
+ * @private Undocumented.
508
+ */
509
+ redirectUri?: string
510
+
511
+ /**
512
+ * @private Undocumented.
513
+ */
514
+ sessionId?: string
515
+
516
+ /**
517
+ * @private Undocumented.
518
+ */
519
+ profile?: KeycloakProfile
520
+
521
+ /**
522
+ * @private Undocumented.
523
+ */
524
+ userInfo?: KeycloakUserInfo
525
+
526
+ /**
527
+ * Called when the adapter is initialized.
528
+ */
529
+ onReady? (authenticated?: boolean): void
530
+
531
+ /**
532
+ * Called when a user is successfully authenticated.
533
+ */
534
+ onAuthSuccess? (): void
535
+
536
+ /**
537
+ * Called if there was an error during authentication.
538
+ */
539
+ onAuthError? (errorData?: KeycloakError): void
540
+
541
+ /**
542
+ * Called when the token is refreshed.
543
+ */
544
+ onAuthRefreshSuccess? (): void
545
+
546
+ /**
547
+ * Called if there was an error while trying to refresh the token.
548
+ */
549
+ onAuthRefreshError? (): void
550
+
551
+ /**
552
+ * Called if the user is logged out (will only be called if the session
553
+ * status iframe is enabled, or in Cordova mode).
554
+ */
555
+ onAuthLogout? (): void
556
+
557
+ /**
558
+ * Called when the access token is expired. If a refresh token is available
559
+ * the token can be refreshed with Keycloak#updateToken, or in cases where
560
+ * it's not (ie. with implicit flow) you can redirect to login screen to
561
+ * obtain a new access token.
562
+ */
563
+ onTokenExpired? (): void
564
+
565
+ /**
566
+ * Called when a AIA has been requested by the application.
567
+ * @param status the outcome of the required action
568
+ * @param action the alias name of the required action, e.g. UPDATE_PASSWORD, CONFIGURE_TOTP etc.
569
+ */
570
+ onActionUpdate? (status: 'success' | 'cancelled' | 'error', action?: string): void
571
+
572
+ /**
573
+ * Called to initialize the adapter.
574
+ * @param initOptions Initialization options.
575
+ * @returns A promise to set functions to be invoked on success or error.
576
+ */
577
+ init (initOptions?: KeycloakInitOptions): Promise<boolean>
578
+
579
+ /**
580
+ * Redirects to login form.
581
+ * @param options Login options.
582
+ */
583
+ login (options?: KeycloakLoginOptions): Promise<void>
584
+
585
+ /**
586
+ * Redirects to logout.
587
+ * @param options Logout options.
588
+ */
589
+ logout (options?: KeycloakLogoutOptions): Promise<void>
590
+
591
+ /**
592
+ * Redirects to registration form.
593
+ * @param options The options used for the registration.
594
+ */
595
+ register (options?: KeycloakRegisterOptions): Promise<void>
596
+
597
+ /**
598
+ * Redirects to the Account Management Console.
599
+ */
600
+ accountManagement (): Promise<void>
601
+
602
+ /**
603
+ * Returns the URL to login form.
604
+ * @param options Supports same options as Keycloak#login.
605
+ */
606
+ createLoginUrl (options?: KeycloakLoginOptions): Promise<string>
607
+
608
+ /**
609
+ * Returns the URL to logout the user.
610
+ * @param options Logout options.
611
+ */
612
+ createLogoutUrl (options?: KeycloakLogoutOptions): string
613
+
614
+ /**
615
+ * Returns the URL to registration page.
616
+ * @param options The options used for creating the registration URL.
617
+ */
618
+ createRegisterUrl (options?: KeycloakRegisterOptions): Promise<string>
619
+
620
+ /**
621
+ * Returns the URL to the Account Management Console.
622
+ * @param options The options used for creating the account URL.
623
+ */
624
+ createAccountUrl (options?: KeycloakAccountOptions): string
625
+
626
+ /**
627
+ * Returns true if the token has less than `minValidity` seconds left before
628
+ * it expires.
629
+ * @param minValidity If not specified, `0` is used.
630
+ */
631
+ isTokenExpired (minValidity?: number): boolean
632
+
633
+ /**
634
+ * If the token expires within `minValidity` seconds, the token is refreshed.
635
+ * If the session status iframe is enabled, the session status is also
636
+ * checked.
637
+ * @param minValidity If not specified, `5` is used.
638
+ * @returns A promise to set functions that can be invoked if the token is
639
+ * still valid, or if the token is no longer valid.
640
+ * @example
641
+ * ```js
642
+ * keycloak.updateToken(5).then(function(refreshed) {
643
+ * if (refreshed) {
644
+ * alert('Token was successfully refreshed');
645
+ * } else {
646
+ * alert('Token is still valid');
647
+ * }
648
+ * }).catch(function() {
649
+ * alert('Failed to refresh the token, or the session has expired');
650
+ * });
651
+ */
652
+ updateToken (minValidity?: number): Promise<boolean>
653
+
654
+ /**
655
+ * Clears authentication state, including tokens. This can be useful if
656
+ * the application has detected the session was expired, for example if
657
+ * updating token fails. Invoking this results in Keycloak#onAuthLogout
658
+ * callback listener being invoked.
659
+ */
660
+ clearToken (): void
661
+
662
+ /**
663
+ * Returns true if the token has the given realm role.
664
+ * @param role A realm role name.
665
+ */
666
+ hasRealmRole (role: string): boolean
667
+
668
+ /**
669
+ * Returns true if the token has the given role for the resource.
670
+ * @param role A role name.
671
+ * @param resource If not specified, `clientId` is used.
672
+ */
673
+ hasResourceRole (role: string, resource?: string): boolean
674
+
675
+ /**
676
+ * Loads the user's profile.
677
+ * @returns A promise to set functions to be invoked on success or error.
678
+ */
679
+ loadUserProfile (): Promise<KeycloakProfile>
680
+
681
+ /**
682
+ * @private Undocumented.
683
+ */
684
+ loadUserInfo (): Promise<KeycloakUserInfo>
685
+ }
686
+
687
+ export default Keycloak
688
+
689
+ /**
690
+ * @deprecated The 'Keycloak' namespace is deprecated, use named imports instead.
691
+ */
692
+ export as namespace Keycloak;