keycloak-angular 19.0.2 → 20.1.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.
package/index.d.ts CHANGED
@@ -1,5 +1,1536 @@
1
+ import { HttpRequest, HttpHeaders, HttpInterceptor, HttpHandler, HttpEvent, HttpHandlerFn } from '@angular/common/http';
2
+ import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, CanActivateFn, CanActivateChildFn } from '@angular/router';
3
+ import * as rxjs from 'rxjs';
4
+ import { Subject, Observable } from 'rxjs';
5
+ import * as Keycloak$1 from 'keycloak-js';
6
+ import Keycloak__default, { KeycloakLogoutOptions, KeycloakLoginOptions, KeycloakError, KeycloakConfig, KeycloakInitOptions } from 'keycloak-js';
7
+ import * as i0 from '@angular/core';
8
+ import { OnChanges, InjectionToken, OnDestroy, Signal, Provider, EnvironmentProviders } from '@angular/core';
9
+ import * as i1 from '@angular/common';
10
+
1
11
  /**
2
- * Generated bundle index. Do not edit.
12
+ * @license
13
+ * Copyright Mauricio Gemelli Vigolo and contributors.
14
+ *
15
+ * Use of this source code is governed by a MIT-style license that can be
16
+ * found in the LICENSE file at https://github.com/mauriciovigolo/keycloak-angular/blob/main/LICENSE.md
3
17
  */
4
- /// <amd-module name="keycloak-angular" />
5
- export * from './public_api';
18
+ /**
19
+ * Keycloak event types, as described at the keycloak-js documentation:
20
+ * https://www.keycloak.org/docs/latest/securing_apps/index.html#callback-events
21
+ *
22
+ * @deprecated Keycloak Event based on the KeycloakService is deprecated and
23
+ * will be removed in future versions.
24
+ * Use the new `KEYCLOAK_EVENT_SIGNAL` injection token to listen for the keycloak
25
+ * events.
26
+ * More info: https://github.com/mauriciovigolo/keycloak-angular/blob/main/docs/migration-guides/v19.md
27
+ */
28
+ declare enum KeycloakEventTypeLegacy {
29
+ /**
30
+ * Called if there was an error during authentication.
31
+ */
32
+ OnAuthError = 0,
33
+ /**
34
+ * Called if the user is logged out
35
+ * (will only be called if the session status iframe is enabled, or in Cordova mode).
36
+ */
37
+ OnAuthLogout = 1,
38
+ /**
39
+ * Called if there was an error while trying to refresh the token.
40
+ */
41
+ OnAuthRefreshError = 2,
42
+ /**
43
+ * Called when the token is refreshed.
44
+ */
45
+ OnAuthRefreshSuccess = 3,
46
+ /**
47
+ * Called when a user is successfully authenticated.
48
+ */
49
+ OnAuthSuccess = 4,
50
+ /**
51
+ * Called when the adapter is initialized.
52
+ */
53
+ OnReady = 5,
54
+ /**
55
+ * Called when the access token is expired. If a refresh token is available the token
56
+ * can be refreshed with updateToken, or in cases where it is not (that is, with implicit flow)
57
+ * you can redirect to login screen to obtain a new access token.
58
+ */
59
+ OnTokenExpired = 6,
60
+ /**
61
+ * Called when a AIA has been requested by the application.
62
+ */
63
+ OnActionUpdate = 7
64
+ }
65
+ /**
66
+ * Structure of an event triggered by Keycloak, contains it's type
67
+ * and arguments (if any).
68
+ *
69
+ * @deprecated Keycloak Event based on the KeycloakService is deprecated and
70
+ * will be removed in future versions.
71
+ * Use the new `KEYCLOAK_EVENT_SIGNAL` injection token to listen for the keycloak
72
+ * events.
73
+ * More info: https://github.com/mauriciovigolo/keycloak-angular/blob/main/docs/migration-guides/v19.md
74
+ */
75
+ interface KeycloakEventLegacy {
76
+ /**
77
+ * Event type as described at {@link KeycloakEventTypeLegacy}.
78
+ */
79
+ type: KeycloakEventTypeLegacy;
80
+ /**
81
+ * Arguments from the keycloak-js event function.
82
+ */
83
+ args?: unknown;
84
+ }
85
+
86
+ /**
87
+ * @license
88
+ * Copyright Mauricio Gemelli Vigolo and contributors.
89
+ *
90
+ * Use of this source code is governed by a MIT-style license that can be
91
+ * found in the LICENSE file at https://github.com/mauriciovigolo/keycloak-angular/blob/main/LICENSE.md
92
+ */
93
+
94
+ /**
95
+ * HTTP Methods
96
+ *
97
+ * @deprecated KeycloakBearerInterceptor is deprecated and will be removed in future versions.
98
+ * Use the new functional interceptor `includeBearerTokenInterceptor`.
99
+ * More info: https://github.com/mauriciovigolo/keycloak-angular/blob/main/docs/migration-guides/v19.md
100
+ */
101
+ type HttpMethodsLegacy = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'PATCH';
102
+ /**
103
+ * ExcludedUrl type may be used to specify the url and the HTTP method that
104
+ * should not be intercepted by the KeycloakBearerInterceptor.
105
+ *
106
+ * Example:
107
+ * const excludedUrl: ExcludedUrl[] = [
108
+ * {
109
+ * url: 'reports/public'
110
+ * httpMethods: ['GET']
111
+ * }
112
+ * ]
113
+ *
114
+ * In the example above for URL reports/public and HTTP Method GET the
115
+ * bearer will not be automatically added.
116
+ *
117
+ * If the url is informed but httpMethod is undefined, then the bearer
118
+ * will not be added for all HTTP Methods.
119
+ *
120
+ * @deprecated KeycloakBearerInterceptor is deprecated and will be removed in future versions.
121
+ * Use the new functional interceptor `includeBearerTokenInterceptor`.
122
+ * More info: https://github.com/mauriciovigolo/keycloak-angular/blob/main/docs/migration-guides/v19.md
123
+ */
124
+ interface ExcludedUrl {
125
+ url: string;
126
+ httpMethods?: HttpMethodsLegacy[];
127
+ }
128
+ /**
129
+ * Similar to ExcludedUrl, contains the HTTP methods and a regex to
130
+ * include the url patterns.
131
+ * This interface is used internally by the KeycloakService.
132
+ *
133
+ * @deprecated KeycloakBearerInterceptor is deprecated and will be removed in future versions.
134
+ * Use the new functional interceptor `includeBearerTokenInterceptor`.
135
+ * More info: https://github.com/mauriciovigolo/keycloak-angular/blob/main/docs/migration-guides/v19.md
136
+ */
137
+ interface ExcludedUrlRegex {
138
+ urlPattern: RegExp;
139
+ httpMethods?: HttpMethodsLegacy[];
140
+ }
141
+ /**
142
+ * keycloak-angular initialization options.
143
+ *
144
+ * @deprecated KeycloakService is deprecated and will be removed in future versions.
145
+ * Use the new `provideKeycloak` method to load Keycloak in an Angular application.
146
+ * More info: https://github.com/mauriciovigolo/keycloak-angular/blob/main/docs/migration-guides/v19.md
147
+ */
148
+ interface KeycloakOptions {
149
+ /**
150
+ * Configs to init the keycloak-js library. If undefined, will look for a keycloak.json file
151
+ * at root of the project.
152
+ * If not undefined, can be a string meaning the url to the keycloak.json file or an object
153
+ * of {@link Keycloak.KeycloakConfig}. Use this configuration if you want to specify the keycloak server,
154
+ * realm, clientId. This is usefull if you have different configurations for production, stage
155
+ * and development environments. Hint: Make use of Angular environment configuration.
156
+ */
157
+ config?: string | Keycloak.KeycloakConfig;
158
+ /**
159
+ * Options to initialize the Keycloak adapter, matches the options as provided by Keycloak itself.
160
+ */
161
+ initOptions?: Keycloak.KeycloakInitOptions;
162
+ /**
163
+ * By default all requests made by Angular HttpClient will be intercepted in order to
164
+ * add the bearer in the Authorization Http Header. However, if this is a not desired
165
+ * feature, the enableBearerInterceptor must be false.
166
+ *
167
+ * Briefly, if enableBearerInterceptor === false, the bearer will not be added
168
+ * to the authorization header.
169
+ *
170
+ * The default value is true.
171
+ */
172
+ enableBearerInterceptor?: boolean;
173
+ /**
174
+ * Forces the execution of loadUserProfile after the keycloak initialization considering that the
175
+ * user logged in.
176
+ * This option is recommended if is desirable to have the user details at the beginning,
177
+ * so after the login, the loadUserProfile function will be called and its value cached.
178
+ *
179
+ * The default value is true.
180
+ */
181
+ loadUserProfileAtStartUp?: boolean;
182
+ /**
183
+ * @deprecated
184
+ * String Array to exclude the urls that should not have the Authorization Header automatically
185
+ * added. This library makes use of Angular Http Interceptor, to automatically add the Bearer
186
+ * token to the request.
187
+ */
188
+ bearerExcludedUrls?: (string | ExcludedUrl)[];
189
+ /**
190
+ * This value will be used as the Authorization Http Header name. The default value is
191
+ * **Authorization**. If the backend expects requests to have a token in a different header, you
192
+ * should change this value, i.e: **JWT-Authorization**. This will result in a Http Header
193
+ * Authorization as "JWT-Authorization: bearer <token>".
194
+ */
195
+ authorizationHeaderName?: string;
196
+ /**
197
+ * This value will be included in the Authorization Http Header param. The default value is
198
+ * **Bearer**, which will result in a Http Header Authorization as "Authorization: Bearer <token>".
199
+ *
200
+ * If any other value is needed by the backend in the authorization header, you should change this
201
+ * value.
202
+ *
203
+ * Warning: this value must be in compliance with the keycloak server instance and the adapter.
204
+ */
205
+ bearerPrefix?: string;
206
+ /**
207
+ * This value will be used to determine whether or not the token needs to be updated. If the token
208
+ * will expire is fewer seconds than the updateMinValidity value, then it will be updated.
209
+ *
210
+ * The default value is 20.
211
+ */
212
+ updateMinValidity?: number;
213
+ /**
214
+ * A function that will tell the KeycloakBearerInterceptor whether to add the token to the request
215
+ * or to leave the request as it is. If the returned value is `true`, the request will have the token
216
+ * present on it. If it is `false`, the token will be left off the request.
217
+ *
218
+ * The default is a function that always returns `true`.
219
+ */
220
+ shouldAddToken?: (request: HttpRequest<unknown>) => boolean;
221
+ /**
222
+ * A function that will tell the KeycloakBearerInterceptor if the token should be considered for
223
+ * updating as a part of the request being made. If the returned value is `true`, the request will
224
+ * check the token's expiry time and if it is less than the number of seconds configured by
225
+ * updateMinValidity then it will be updated before the request is made. If the returned value is
226
+ * false, the token will not be updated.
227
+ *
228
+ * The default is a function that always returns `true`.
229
+ */
230
+ shouldUpdateToken?: (request: HttpRequest<unknown>) => boolean;
231
+ }
232
+
233
+ /**
234
+ * Service to expose existent methods from the Keycloak JS adapter, adding new
235
+ * functionalities to improve the use of keycloak in Angular v > 4.3 applications.
236
+ *
237
+ * This class should be injected in the application bootstrap, so the same instance will be used
238
+ * along the web application.
239
+ *
240
+ * @deprecated This service is deprecated and will be removed in future versions.
241
+ * Use the new `provideKeycloak` function to load Keycloak in an Angular application.
242
+ * More info: https://github.com/mauriciovigolo/keycloak-angular/blob/main/docs/migration-guides/v19.md
243
+ */
244
+ declare class KeycloakService {
245
+ /**
246
+ * Keycloak-js instance.
247
+ */
248
+ private _instance;
249
+ /**
250
+ * User profile as KeycloakProfile interface.
251
+ */
252
+ private _userProfile;
253
+ /**
254
+ * Flag to indicate if the bearer will not be added to the authorization header.
255
+ */
256
+ private _enableBearerInterceptor;
257
+ /**
258
+ * When the implicit flow is choosen there must exist a silentRefresh, as there is
259
+ * no refresh token.
260
+ */
261
+ private _silentRefresh;
262
+ /**
263
+ * Indicates that the user profile should be loaded at the keycloak initialization,
264
+ * just after the login.
265
+ */
266
+ private _loadUserProfileAtStartUp;
267
+ /**
268
+ * The bearer prefix that will be appended to the Authorization Header.
269
+ */
270
+ private _bearerPrefix;
271
+ /**
272
+ * Value that will be used as the Authorization Http Header name.
273
+ */
274
+ private _authorizationHeaderName;
275
+ /**
276
+ * @deprecated
277
+ * The excluded urls patterns that must skip the KeycloakBearerInterceptor.
278
+ */
279
+ private _excludedUrls;
280
+ /**
281
+ * Observer for the keycloak events
282
+ */
283
+ private _keycloakEvents$;
284
+ /**
285
+ * The amount of required time remaining before expiry of the token before the token will be refreshed.
286
+ */
287
+ private _updateMinValidity;
288
+ /**
289
+ * Returns true if the request should have the token added to the headers by the KeycloakBearerInterceptor.
290
+ */
291
+ shouldAddToken: (request: HttpRequest<unknown>) => boolean;
292
+ /**
293
+ * Returns true if the request being made should potentially update the token.
294
+ */
295
+ shouldUpdateToken: (request: HttpRequest<unknown>) => boolean;
296
+ /**
297
+ * Binds the keycloak-js events to the keycloakEvents Subject
298
+ * which is a good way to monitor for changes, if needed.
299
+ *
300
+ * The keycloakEvents returns the keycloak-js event type and any
301
+ * argument if the source function provides any.
302
+ */
303
+ private bindsKeycloakEvents;
304
+ /**
305
+ * Loads all bearerExcludedUrl content in a uniform type: ExcludedUrl,
306
+ * so it becomes easier to handle.
307
+ *
308
+ * @param bearerExcludedUrls array of strings or ExcludedUrl that includes
309
+ * the url and HttpMethod.
310
+ */
311
+ private loadExcludedUrls;
312
+ /**
313
+ * Handles the class values initialization.
314
+ *
315
+ * @param options
316
+ */
317
+ private initServiceValues;
318
+ /**
319
+ * Keycloak initialization. It should be called to initialize the adapter.
320
+ * Options is an object with 2 main parameters: config and initOptions. The first one
321
+ * will be used to create the Keycloak instance. The second one are options to initialize the
322
+ * keycloak instance.
323
+ *
324
+ * @param options
325
+ * Config: may be a string representing the keycloak URI or an object with the
326
+ * following content:
327
+ * - url: Keycloak json URL
328
+ * - realm: realm name
329
+ * - clientId: client id
330
+ *
331
+ * initOptions:
332
+ * Options to initialize the Keycloak adapter, matches the options as provided by Keycloak itself.
333
+ *
334
+ * enableBearerInterceptor:
335
+ * Flag to indicate if the bearer will added to the authorization header.
336
+ *
337
+ * loadUserProfileInStartUp:
338
+ * Indicates that the user profile should be loaded at the keycloak initialization,
339
+ * just after the login.
340
+ *
341
+ * bearerExcludedUrls:
342
+ * String Array to exclude the urls that should not have the Authorization Header automatically
343
+ * added.
344
+ *
345
+ * authorizationHeaderName:
346
+ * This value will be used as the Authorization Http Header name.
347
+ *
348
+ * bearerPrefix:
349
+ * This value will be included in the Authorization Http Header param.
350
+ *
351
+ * tokenUpdateExcludedHeaders:
352
+ * Array of Http Header key/value maps that should not trigger the token to be updated.
353
+ *
354
+ * updateMinValidity:
355
+ * This value determines if the token will be refreshed based on its expiration time.
356
+ *
357
+ * @returns
358
+ * A Promise with a boolean indicating if the initialization was successful.
359
+ */
360
+ init(options?: KeycloakOptions): Promise<boolean>;
361
+ /**
362
+ * Redirects to login form on (options is an optional object with redirectUri and/or
363
+ * prompt fields).
364
+ *
365
+ * @param options
366
+ * Object, where:
367
+ * - redirectUri: Specifies the uri to redirect to after login.
368
+ * - prompt:By default the login screen is displayed if the user is not logged-in to Keycloak.
369
+ * To only authenticate to the application if the user is already logged-in and not display the
370
+ * login page if the user is not logged-in, set this option to none. To always require
371
+ * re-authentication and ignore SSO, set this option to login .
372
+ * - maxAge: Used just if user is already authenticated. Specifies maximum time since the
373
+ * authentication of user happened. If user is already authenticated for longer time than
374
+ * maxAge, the SSO is ignored and he will need to re-authenticate again.
375
+ * - loginHint: Used to pre-fill the username/email field on the login form.
376
+ * - action: If value is 'register' then user is redirected to registration page, otherwise to
377
+ * login page.
378
+ * - locale: Specifies the desired locale for the UI.
379
+ * @returns
380
+ * A void Promise if the login is successful and after the user profile loading.
381
+ */
382
+ login(options?: Keycloak.KeycloakLoginOptions): Promise<void>;
383
+ /**
384
+ * Redirects to logout.
385
+ *
386
+ * @param redirectUri
387
+ * Specifies the uri to redirect to after logout.
388
+ * @returns
389
+ * A void Promise if the logout was successful, cleaning also the userProfile.
390
+ */
391
+ logout(redirectUri?: string): Promise<void>;
392
+ /**
393
+ * Redirects to registration form. Shortcut for login with option
394
+ * action = 'register'. Options are same as for the login method but 'action' is set to
395
+ * 'register'.
396
+ *
397
+ * @param options
398
+ * login options
399
+ * @returns
400
+ * A void Promise if the register flow was successful.
401
+ */
402
+ register(options?: Keycloak.KeycloakLoginOptions): Promise<void>;
403
+ /**
404
+ * Check if the user has access to the specified role. It will look for roles in
405
+ * realm and the given resource, but will not check if the user is logged in for better performance.
406
+ *
407
+ * @param role
408
+ * role name
409
+ * @param resource
410
+ * resource name. If not specified, `clientId` is used
411
+ * @returns
412
+ * A boolean meaning if the user has the specified Role.
413
+ */
414
+ isUserInRole(role: string, resource?: string): boolean;
415
+ /**
416
+ * Return the roles of the logged user. The realmRoles parameter, with default value
417
+ * true, will return the resource roles and realm roles associated with the logged user. If set to false
418
+ * it will only return the resource roles. The resource parameter, if specified, will return only resource roles
419
+ * associated with the given resource.
420
+ *
421
+ * @param realmRoles
422
+ * Set to false to exclude realm roles (only client roles)
423
+ * @param resource
424
+ * resource name If not specified, returns roles from all resources
425
+ * @returns
426
+ * Array of Roles associated with the logged user.
427
+ */
428
+ getUserRoles(realmRoles?: boolean, resource?: string): string[];
429
+ /**
430
+ * Check if user is logged in.
431
+ *
432
+ * @returns
433
+ * A boolean that indicates if the user is logged in.
434
+ */
435
+ isLoggedIn(): boolean;
436
+ /**
437
+ * Returns true if the token has less than minValidity seconds left before
438
+ * it expires.
439
+ *
440
+ * @param minValidity
441
+ * Seconds left. (minValidity) is optional. Default value is 0.
442
+ * @returns
443
+ * Boolean indicating if the token is expired.
444
+ */
445
+ isTokenExpired(minValidity?: number): boolean;
446
+ /**
447
+ * If the token expires within _updateMinValidity seconds the token is refreshed. If the
448
+ * session status iframe is enabled, the session status is also checked.
449
+ * Returns a promise telling if the token was refreshed or not. If the session is not active
450
+ * anymore, the promise is rejected.
451
+ *
452
+ * @param minValidity
453
+ * Seconds left. (minValidity is optional, if not specified updateMinValidity - default 20 is used)
454
+ * @returns
455
+ * Promise with a boolean indicating if the token was succesfully updated.
456
+ */
457
+ updateToken(minValidity?: number): Promise<boolean>;
458
+ /**
459
+ * Loads the user profile.
460
+ * Returns promise to set functions to be invoked if the profile was loaded
461
+ * successfully, or if the profile could not be loaded.
462
+ *
463
+ * @param forceReload
464
+ * If true will force the loadUserProfile even if its already loaded.
465
+ * @returns
466
+ * A promise with the KeycloakProfile data loaded.
467
+ */
468
+ loadUserProfile(forceReload?: boolean): Promise<Keycloak$1.KeycloakProfile>;
469
+ /**
470
+ * Returns the authenticated token.
471
+ */
472
+ getToken(): Promise<string>;
473
+ /**
474
+ * Returns the logged username.
475
+ *
476
+ * @returns
477
+ * The logged username.
478
+ */
479
+ getUsername(): string;
480
+ /**
481
+ * Clear authentication state, including tokens. This can be useful if application
482
+ * has detected the session was expired, for example if updating token fails.
483
+ * Invoking this results in onAuthLogout callback listener being invoked.
484
+ */
485
+ clearToken(): void;
486
+ /**
487
+ * Adds a valid token in header. The key & value format is:
488
+ * Authorization Bearer <token>.
489
+ * If the headers param is undefined it will create the Angular headers object.
490
+ *
491
+ * @param headers
492
+ * Updated header with Authorization and Keycloak token.
493
+ * @returns
494
+ * An observable with with the HTTP Authorization header and the current token.
495
+ */
496
+ addTokenToHeader(headers?: HttpHeaders): rxjs.Observable<HttpHeaders>;
497
+ /**
498
+ * Returns the original Keycloak instance, if you need any customization that
499
+ * this Angular service does not support yet. Use with caution.
500
+ *
501
+ * @returns
502
+ * The KeycloakInstance from keycloak-js.
503
+ */
504
+ getKeycloakInstance(): Keycloak.KeycloakInstance;
505
+ /**
506
+ * @deprecated
507
+ * Returns the excluded URLs that should not be considered by
508
+ * the http interceptor which automatically adds the authorization header in the Http Request.
509
+ *
510
+ * @returns
511
+ * The excluded urls that must not be intercepted by the KeycloakBearerInterceptor.
512
+ */
513
+ get excludedUrls(): ExcludedUrlRegex[];
514
+ /**
515
+ * Flag to indicate if the bearer will be added to the authorization header.
516
+ *
517
+ * @returns
518
+ * Returns if the bearer interceptor was set to be disabled.
519
+ */
520
+ get enableBearerInterceptor(): boolean;
521
+ /**
522
+ * Keycloak subject to monitor the events triggered by keycloak-js.
523
+ * The following events as available (as described at keycloak docs -
524
+ * https://www.keycloak.org/docs/latest/securing_apps/index.html#callback-events):
525
+ * - OnAuthError
526
+ * - OnAuthLogout
527
+ * - OnAuthRefreshError
528
+ * - OnAuthRefreshSuccess
529
+ * - OnAuthSuccess
530
+ * - OnReady
531
+ * - OnTokenExpire
532
+ * In each occurrence of any of these, this subject will return the event type,
533
+ * described at {@link KeycloakEventTypeLegacy} enum and the function args from the keycloak-js
534
+ * if provided any.
535
+ *
536
+ * @returns
537
+ * A subject with the {@link KeycloakEventLegacy} which describes the event type and attaches the
538
+ * function args.
539
+ */
540
+ get keycloakEvents$(): Subject<KeycloakEventLegacy>;
541
+ static ɵfac: i0.ɵɵFactoryDeclaration<KeycloakService, never>;
542
+ static ɵprov: i0.ɵɵInjectableDeclaration<KeycloakService>;
543
+ }
544
+
545
+ /**
546
+ * @license
547
+ * Copyright Mauricio Gemelli Vigolo and contributors.
548
+ *
549
+ * Use of this source code is governed by a MIT-style license that can be
550
+ * found in the LICENSE file at https://github.com/mauriciovigolo/keycloak-angular/blob/main/LICENSE.md
551
+ */
552
+
553
+ /**
554
+ * A simple guard implementation out of the box. This class should be inherited and
555
+ * implemented by the application. The only method that should be implemented is #isAccessAllowed.
556
+ * The reason for this is that the authorization flow is usually not unique, so in this way you will
557
+ * have more freedom to customize your authorization flow.
558
+ *
559
+ * @deprecated Class based guards are deprecated in Keycloak Angular and will be removed in future versions.
560
+ * Use the new `createAuthGuard` function to create a Guard for your application.
561
+ * More info: https://github.com/mauriciovigolo/keycloak-angular/blob/main/docs/migration-guides/v19.md
562
+ */
563
+ declare abstract class KeycloakAuthGuard implements CanActivate {
564
+ protected router: Router;
565
+ protected keycloakAngular: KeycloakService;
566
+ /**
567
+ * Indicates if the user is authenticated or not.
568
+ */
569
+ protected authenticated: boolean;
570
+ /**
571
+ * Roles of the logged user. It contains the clientId and realm user roles.
572
+ */
573
+ protected roles: string[];
574
+ constructor(router: Router, keycloakAngular: KeycloakService);
575
+ /**
576
+ * CanActivate checks if the user is logged in and get the full list of roles (REALM + CLIENT)
577
+ * of the logged user. This values are set to authenticated and roles params.
578
+ *
579
+ * @param route
580
+ * @param state
581
+ */
582
+ canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean | UrlTree>;
583
+ /**
584
+ * Create your own customized authorization flow in this method. From here you already known
585
+ * if the user is authenticated (this.authenticated) and the user roles (this.roles).
586
+ *
587
+ * Return a UrlTree if the user should be redirected to another route.
588
+ *
589
+ * @param route
590
+ * @param state
591
+ */
592
+ abstract isAccessAllowed(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean | UrlTree>;
593
+ }
594
+
595
+ /**
596
+ * This interceptor includes the bearer by default in all HttpClient requests.
597
+ *
598
+ * If you need to exclude some URLs from adding the bearer, please, take a look
599
+ * at the {@link KeycloakOptions} bearerExcludedUrls property.
600
+ *
601
+ * @deprecated KeycloakBearerInterceptor is deprecated and will be removed in future versions.
602
+ * Use the new functional interceptor such as `includeBearerTokenInterceptor`.
603
+ * More info: https://github.com/mauriciovigolo/keycloak-angular/blob/main/docs/migration-guides/v19.md
604
+ */
605
+ declare class KeycloakBearerInterceptor implements HttpInterceptor {
606
+ private keycloak;
607
+ /**
608
+ * Calls to update the keycloak token if the request should update the token.
609
+ *
610
+ * @param req http request from @angular http module.
611
+ * @returns
612
+ * A promise boolean for the token update or noop result.
613
+ */
614
+ private conditionallyUpdateToken;
615
+ /**
616
+ * @deprecated
617
+ * Checks if the url is excluded from having the Bearer Authorization
618
+ * header added.
619
+ *
620
+ * @param req http request from @angular http module.
621
+ * @param excludedUrlRegex contains the url pattern and the http methods,
622
+ * excluded from adding the bearer at the Http Request.
623
+ */
624
+ private isUrlExcluded;
625
+ /**
626
+ * Intercept implementation that checks if the request url matches the excludedUrls.
627
+ * If not, adds the Authorization header to the request if the user is logged in.
628
+ *
629
+ * @param req
630
+ * @param next
631
+ */
632
+ intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>>;
633
+ /**
634
+ * Adds the token of the current user to the Authorization header
635
+ *
636
+ * @param req
637
+ * @param next
638
+ */
639
+ private handleRequestWithTokenHeader;
640
+ static ɵfac: i0.ɵɵFactoryDeclaration<KeycloakBearerInterceptor, never>;
641
+ static ɵprov: i0.ɵɵInjectableDeclaration<KeycloakBearerInterceptor>;
642
+ }
643
+
644
+ /**
645
+ * @deprecated NgModules are deprecated in Keycloak Angular and will be removed in future versions.
646
+ * Use the new `provideKeycloak` function to load Keycloak in an Angular application.
647
+ * More info: https://github.com/mauriciovigolo/keycloak-angular/blob/main/docs/migration-guides/v19.md
648
+ */
649
+ declare class CoreModule {
650
+ static ɵfac: i0.ɵɵFactoryDeclaration<CoreModule, never>;
651
+ static ɵmod: i0.ɵɵNgModuleDeclaration<CoreModule, never, [typeof i1.CommonModule], never>;
652
+ static ɵinj: i0.ɵɵInjectorDeclaration<CoreModule>;
653
+ }
654
+
655
+ /**
656
+ * @deprecated NgModules are deprecated in Keycloak Angular and will be removed in future versions.
657
+ * Use the new `provideKeycloak` function to load Keycloak in an Angular application.
658
+ * More info: https://github.com/mauriciovigolo/keycloak-angular/blob/main/docs/migration-guides/v19.md
659
+ */
660
+ declare class KeycloakAngularModule {
661
+ static ɵfac: i0.ɵɵFactoryDeclaration<KeycloakAngularModule, never>;
662
+ static ɵmod: i0.ɵɵNgModuleDeclaration<KeycloakAngularModule, never, [typeof CoreModule], never>;
663
+ static ɵinj: i0.ɵɵInjectorDeclaration<KeycloakAngularModule>;
664
+ }
665
+
666
+ /**
667
+ * @license
668
+ * Copyright Mauricio Gemelli Vigolo All Rights Reserved.
669
+ *
670
+ * Use of this source code is governed by a MIT-style license that can be
671
+ * found in the LICENSE file at https://github.com/mauriciovigolo/keycloak-angular/blob/main/LICENSE.md
672
+ */
673
+
674
+ /**
675
+ * Structural directive to conditionally display elements based on Keycloak user roles.
676
+ *
677
+ * This directive checks if the authenticated user has at least one of the specified roles.
678
+ * Roles can be validated against a specific **resource (client ID)** or the **realm**.
679
+ *
680
+ * ### Features:
681
+ * - Supports role checking in both **resources (client-level roles)** and the **realm**.
682
+ * - Accepts an array of roles to match.
683
+ * - Optional configuration to check realm-level roles.
684
+ *
685
+ * ### Inputs:
686
+ * - `kaHasRoles` (Required): Array of roles to validate.
687
+ * - `resource` (Optional): The client ID or resource name to validate resource-level roles.
688
+ * - `checkRealm` (Optional): A boolean flag to enable realm role validation (default is `false`).
689
+ *
690
+ * ### Requirements:
691
+ * - A Keycloak instance must be injected via Angular's dependency injection.
692
+ * - The user must be authenticated in Keycloak.
693
+ *
694
+ * @example
695
+ * #### Example 1: Check for Global Realm Roles
696
+ * Show the content only if the user has the `admin` or `editor` role in the realm.
697
+ * ```html
698
+ * <div *kaHasRoles="['admin', 'editor']; checkRealm:true">
699
+ * <p>This content is visible only to users with 'admin' or 'editor' realm roles.</p>
700
+ * </div>
701
+ * ```
702
+ *
703
+ * @example
704
+ * #### Example 2: Check for Resource Roles
705
+ * Show the content only if the user has the `read` or `write` role for a specific resource (`my-client`).
706
+ * ```html
707
+ * <div *kaHasRoles="['read', 'write']; resource:'my-client'">
708
+ * <p>This content is visible only to users with 'read' or 'write' roles for 'my-client'.</p>
709
+ * </div>
710
+ * ```
711
+ *
712
+ * @example
713
+ * #### Example 3: Check for Both Resource and Realm Roles
714
+ * Show the content if the user has the roles in either the realm or a resource.
715
+ * ```html
716
+ * <div *kaHasRoles="['admin', 'write']; resource:'my-client' checkRealm:true">
717
+ * <p>This content is visible to users with 'admin' in the realm or 'write' in 'my-client'.</p>
718
+ * </div>
719
+ * ```
720
+ *
721
+ * @example
722
+ * #### Example 4: Fallback Content When Roles Do Not Match
723
+ * Use an `<ng-template>` to display fallback content if the user lacks the required roles.
724
+ * ```html
725
+ * <div *kaHasRoles="['admin']; resource:'my-client'">
726
+ * <p>Welcome, Admin!</p>
727
+ * </div>
728
+ * <ng-template #noAccess>
729
+ * <p>Access Denied</p>
730
+ * </ng-template>
731
+ * ```
732
+ */
733
+ declare class HasRolesDirective implements OnChanges {
734
+ private templateRef;
735
+ private viewContainer;
736
+ private keycloak;
737
+ /**
738
+ * List of roles to validate against the resource or realm.
739
+ */
740
+ roles: string[];
741
+ /**
742
+ * The resource (client ID) to validate roles against.
743
+ */
744
+ resource?: string;
745
+ /**
746
+ * Flag to enable realm-level role validation.
747
+ */
748
+ checkRealm: boolean;
749
+ constructor();
750
+ /**
751
+ * Here to reevaluate access when inputs change.
752
+ */
753
+ ngOnChanges(): void;
754
+ /**
755
+ * Clear the view and render it if user has access.
756
+ */
757
+ private render;
758
+ /**
759
+ * Checks if the user has at least one of the specified roles in the resource or realm.
760
+ * @returns True if the user has access, false otherwise.
761
+ */
762
+ private checkUserRoles;
763
+ static ɵfac: i0.ɵɵFactoryDeclaration<HasRolesDirective, never>;
764
+ static ɵdir: i0.ɵɵDirectiveDeclaration<HasRolesDirective, "[kaHasRoles]", never, { "roles": { "alias": "kaHasRoles"; "required": false; }; "resource": { "alias": "kaHasRolesResource"; "required": false; }; "checkRealm": { "alias": "kaHasRolesCheckRealm"; "required": false; }; }, {}, never, never, true, never>;
765
+ }
766
+
767
+ /**
768
+ * @license
769
+ * Copyright Mauricio Gemelli Vigolo All Rights Reserved.
770
+ *
771
+ * Use of this source code is governed by a MIT-style license that can be
772
+ * found in the LICENSE file at https://github.com/mauriciovigolo/keycloak-angular/blob/main/LICENSE.md
773
+ */
774
+ /**
775
+ * Represents a feature from keycloak-angular that can be configured during the library initialization.
776
+ *
777
+ * This type defines the structure of a feature that includes a `configure` method,
778
+ * which is responsible for setting up or initializing the feature's behavior or properties
779
+ * related to Keycloak.
780
+ *
781
+ * ### Usage:
782
+ * The `KeycloakFeature` type is typically used for defining modular, reusable Keycloak
783
+ * features that can be dynamically configured and integrated into an application.
784
+ *
785
+ * @property {() => void} configure - A method that initializes or configures the feature.
786
+ * This method is invoked to perform any setup or customization required for the feature.
787
+ *
788
+ * ### Example:
789
+ * ```typescript
790
+ * const withLoggingFeature: KeycloakFeature = {
791
+ * configure: () => {
792
+ * console.log('Configuring Keycloak logging feature');
793
+ * },
794
+ * };
795
+ *
796
+ * const withAnalyticsFeature: KeycloakFeature = {
797
+ * configure: () => {
798
+ * console.log('Configuring Keycloak analytics feature');
799
+ * },
800
+ * };
801
+ *
802
+ * // Configure and initialize features
803
+ * withLoggingFeature.configure();
804
+ * withAnalyticsFeature.configure();
805
+ * ```
806
+ */
807
+ type KeycloakFeature = {
808
+ configure: () => void;
809
+ };
810
+
811
+ /**
812
+ * @license
813
+ * Copyright Mauricio Gemelli Vigolo All Rights Reserved.
814
+ *
815
+ * Use of this source code is governed by a MIT-style license that can be
816
+ * found in the LICENSE file at https://github.com/mauriciovigolo/keycloak-angular/blob/main/LICENSE.md
817
+ */
818
+
819
+ /**
820
+ * Options for configuring the auto-refresh token feature.
821
+ *
822
+ * This type defines the configuration parameters for enabling auto-refresh
823
+ * of Keycloak tokens and handling session inactivity scenarios.
824
+ */
825
+ type WithRefreshTokenOptions = {
826
+ /**
827
+ * The session timeout duration in milliseconds. This specifies the time
828
+ * of inactivity after which the session is considered expired.
829
+ *
830
+ * Default value: `300000` milliseconds (5 minutes).
831
+ */
832
+ sessionTimeout?: number;
833
+ /**
834
+ * Action to take when the session timeout due to inactivity occurs.
835
+ *
836
+ * - `'login'`: Execute the `keycloak.login` method.
837
+ * - `'logout'`: Logs the user out by calling the `keycloak.logout` method.
838
+ * - `'none'`: Takes no action on session timeout.
839
+ *
840
+ * Default value: `'logout'`.
841
+ */
842
+ onInactivityTimeout?: 'login' | 'logout' | 'none';
843
+ /**
844
+ * Logout options to pass to keycloak.logout when the user is getting logged out automatically after timout.
845
+ *
846
+ * Default value: undefined
847
+ */
848
+ logoutOptions?: KeycloakLogoutOptions;
849
+ /**
850
+ * Login options to pass to keycloak.login when the user is getting logged in automatically after timeout.
851
+ *
852
+ * Default value: undefined
853
+ */
854
+ loginOptions?: KeycloakLoginOptions;
855
+ };
856
+ /**
857
+ * Enables automatic token refresh and session inactivity handling for a
858
+ * Keycloak-enabled Angular application.
859
+ *
860
+ * This function initializes a service that tracks user interactions, such as
861
+ * mouse movements, touches, key presses, clicks, and scrolls. If user activity
862
+ * is detected, it periodically calls `Keycloak.updateToken` to ensure the bearer
863
+ * token remains valid and does not expire.
864
+ *
865
+ * If the session remains inactive beyond the defined `sessionTimeout`, the
866
+ * specified action (`logout`, `login`, or `none`) will be executed. By default,
867
+ * the service will call `keycloak.logout` upon inactivity timeout.
868
+ *
869
+ * Event tracking uses RxJS observables with a debounce of 300 milliseconds to
870
+ * monitor user interactions. When the Keycloak `OnTokenExpired` event occurs,
871
+ * the service checks the user's last activity timestamp. If the user has been
872
+ * active within the session timeout period, it refreshes the token using `updateToken`.
873
+ *
874
+ *
875
+ * @param options - Configuration options for the auto-refresh token feature.
876
+ * - `sessionTimeout` (optional): The duration in milliseconds after which
877
+ * the session is considered inactive. Defaults to `300000` (5 minutes).
878
+ * - `onInactivityTimeout` (optional): The action to take when session inactivity
879
+ * exceeds the specified timeout. Defaults to `'logout'`.
880
+ * - `'login'`: Execute `keycloak.login` function.
881
+ * - `'logout'`: Logs the user out by calling `keycloak.logout`.
882
+ * - `'none'`: No action is taken.
883
+ * - `logoutOptions` (optional): Logout options to pass to keycloak.logout
884
+ * when the user is getting logged out automatically after timout.
885
+ * - `loginOptions` (optional): Login options to pass to keycloak.login
886
+ * when the user is getting logged in automatically after timout.
887
+ *
888
+ * @returns A `KeycloakFeature` instance that configures and enables the
889
+ * auto-refresh token functionality.
890
+ */
891
+ declare function withAutoRefreshToken(options?: WithRefreshTokenOptions): KeycloakFeature;
892
+
893
+ /**
894
+ * @license
895
+ * Copyright Mauricio Gemelli Vigolo All Rights Reserved.
896
+ *
897
+ * Use of this source code is governed by a MIT-style license that can be
898
+ * found in the LICENSE file at https://github.com/mauriciovigolo/keycloak-angular/blob/main/LICENSE.md
899
+ */
900
+
901
+ /**
902
+ * Type representing the roles granted to a user, including both realm and resource-level roles.
903
+ */
904
+ type Roles = {
905
+ /**
906
+ * Roles assigned at the realm level.
907
+ */
908
+ realmRoles: string[];
909
+ /**
910
+ * Roles assigned at the resource level, organized by resource name.
911
+ */
912
+ resourceRoles: {
913
+ [resource: string]: string[];
914
+ };
915
+ };
916
+ /**
917
+ * Data structure passed to the custom authorization guard to determine access.
918
+ */
919
+ type AuthGuardData = {
920
+ /**
921
+ * Indicates whether the user is currently authenticated.
922
+ */
923
+ authenticated: boolean;
924
+ /**
925
+ * A collection of roles granted to the user, including both realm and resource roles.
926
+ */
927
+ grantedRoles: Roles;
928
+ /**
929
+ * The Keycloak instance managing the user's session and access.
930
+ */
931
+ keycloak: Keycloak__default;
932
+ };
933
+ /**
934
+ * Creates a custom authorization guard for Angular routes, enabling fine-grained access control.
935
+ *
936
+ * This guard invokes the provided `isAccessAllowed` function to determine if access is permitted
937
+ * based on the current route, router state, and user's authentication and roles data.
938
+ *
939
+ * @template T - The type of the guard function (`CanActivateFn` or `CanActivateChildFn`).
940
+ * @param isAccessAllowed - A callback function that evaluates access conditions. The function receives:
941
+ * - `route`: The current `ActivatedRouteSnapshot` for the route being accessed.
942
+ * - `state`: The current `RouterStateSnapshot` representing the router's state.
943
+ * - `authData`: An `AuthGuardData` object containing the user's authentication status, roles, and Keycloak instance.
944
+ * @returns A guard function of type `T` that can be used as a route `canActivate` or `canActivateChild` guard.
945
+ *
946
+ * @example
947
+ * ```ts
948
+ * import { createAuthGuard } from './auth-guard';
949
+ * import { Routes } from '@angular/router';
950
+ *
951
+ * const isUserAllowed = async (route, state, authData) => {
952
+ * const { authenticated, grantedRoles } = authData;
953
+ * return authenticated && grantedRoles.realmRoles.includes('admin');
954
+ * };
955
+ *
956
+ * const routes: Routes = [
957
+ * {
958
+ * path: 'admin',
959
+ * canActivate: [createAuthGuard(isUserAllowed)],
960
+ * component: AdminComponent,
961
+ * },
962
+ * ];
963
+ * ```
964
+ */
965
+ declare const createAuthGuard: <T extends CanActivateFn | CanActivateChildFn>(isAccessAllowed: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot, authData: AuthGuardData) => Promise<boolean | UrlTree>) => T;
966
+
967
+ /**
968
+ * @license
969
+ * Copyright Mauricio Gemelli Vigolo All Rights Reserved.
970
+ *
971
+ * Use of this source code is governed by a MIT-style license that can be
972
+ * found in the LICENSE file at https://github.com/mauriciovigolo/keycloak-angular/blob/main/LICENSE.md
973
+ */
974
+
975
+ /**
976
+ * Represents the HTTP methods supported by the interceptor for authorization purposes.
977
+ */
978
+ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'PATCH';
979
+ /**
980
+ * Common attributes for the Auth Bearer interceptor that can be reused in other interceptor implementations.
981
+ */
982
+ type BearerTokenCondition = {
983
+ /**
984
+ * Prefix to be used in the Authorization header. Default is "Bearer".
985
+ * This will result in a header formatted as: `Authorization: Bearer <token>`.
986
+ *
987
+ * Adjust this value if your backend expects a different prefix in the Authorization header.
988
+ */
989
+ bearerPrefix?: string;
990
+ /**
991
+ * Name of the HTTP header used for authorization. Default is "Authorization".
992
+ * Customize this value if your backend expects a different header, e.g., "JWT-Authorization".
993
+ */
994
+ authorizationHeaderName?: string;
995
+ /**
996
+ * Function to determine whether the token should be updated before a request. Default is a function returning true.
997
+ * If the function returns `true`, the token's validity will be checked and updated if needed.
998
+ * If it returns `false`, the token update process will be skipped for that request.
999
+ *
1000
+ * @param request - The current `HttpRequest` object being intercepted.
1001
+ * @returns A boolean indicating whether to update the token.
1002
+ */
1003
+ shouldUpdateToken?: (request: HttpRequest<unknown>) => boolean;
1004
+ };
1005
+ /**
1006
+ * Generic factory function to create an interceptor condition with default values.
1007
+ *
1008
+ * This utility allows you to define custom interceptor conditions while ensuring that
1009
+ * default values are applied to any missing fields. By using generics, you can enforce
1010
+ * strong typing when creating the fields for the interceptor condition, enhancing type safety.
1011
+ *
1012
+ * @template T - A type that extends `AuthBearerCondition`.
1013
+ * @param value - An object of type `T` (extending `AuthBearerCondition`) to be enhanced with default values.
1014
+ * @returns A new object of type `T` with default values assigned to any undefined properties.
1015
+ */
1016
+ declare const createInterceptorCondition: <T extends BearerTokenCondition>(value: T) => T;
1017
+ /**
1018
+ * Conditionally updates the Keycloak token based on the provided request and conditions.
1019
+ *
1020
+ * @param req - The `HttpRequest` object being processed.
1021
+ * @param keycloak - The Keycloak instance managing authentication.
1022
+ * @param condition - An `AuthBearerCondition` object with the `shouldUpdateToken` function.
1023
+ * @returns A `Promise<boolean>` indicating whether the token was successfully updated.
1024
+ */
1025
+ declare const conditionallyUpdateToken: (req: HttpRequest<unknown>, keycloak: Keycloak__default, { shouldUpdateToken }: BearerTokenCondition) => Promise<boolean>;
1026
+ /**
1027
+ * Adds the Authorization header to an HTTP request and forwards it to the next handler.
1028
+ *
1029
+ * @param req - The original `HttpRequest` object.
1030
+ * @param next - The `HttpHandlerFn` function for forwarding the HTTP request.
1031
+ * @param keycloak - The Keycloak instance providing the authentication token.
1032
+ * @param condition - An `AuthBearerCondition` object specifying header configuration.
1033
+ * @returns An `Observable<HttpEvent<unknown>>` representing the HTTP response.
1034
+ */
1035
+ declare const addAuthorizationHeader: (req: HttpRequest<unknown>, next: HttpHandlerFn, keycloak: Keycloak__default, condition: BearerTokenCondition) => Observable<HttpEvent<unknown>>;
1036
+
1037
+ /**
1038
+ * @license
1039
+ * Copyright Mauricio Gemelli Vigolo All Rights Reserved.
1040
+ *
1041
+ * Use of this source code is governed by a MIT-style license that can be
1042
+ * found in the LICENSE file at https://github.com/mauriciovigolo/keycloak-angular/blob/main/LICENSE.md
1043
+ */
1044
+
1045
+ /**
1046
+ * Defines a custom condition for determining whether a Bearer token should be included
1047
+ * in the `Authorization` header of an outgoing HTTP request.
1048
+ *
1049
+ * This type extends the `BearerTokenCondition` type and adds a dynamic function
1050
+ * (`shouldAddToken`) that evaluates whether the token should be added based on the
1051
+ * request, handler, and Keycloak state.
1052
+ */
1053
+ type CustomBearerTokenCondition = Partial<BearerTokenCondition> & {
1054
+ /**
1055
+ * A function that dynamically determines whether the Bearer token should be included
1056
+ * in the `Authorization` header for a given request.
1057
+ *
1058
+ * This function is asynchronous and receives the following arguments:
1059
+ * - `req`: The `HttpRequest` object representing the current outgoing HTTP request.
1060
+ * - `next`: The `HttpHandlerFn` for forwarding the request to the next handler in the chain.
1061
+ * - `keycloak`: The `Keycloak` instance representing the authentication context.
1062
+ */
1063
+ shouldAddToken: (req: HttpRequest<unknown>, next: HttpHandlerFn, keycloak: Keycloak__default) => Promise<boolean>;
1064
+ };
1065
+ /**
1066
+ * Injection token for configuring the `customBearerTokenInterceptor`.
1067
+ *
1068
+ * This injection token holds an array of `CustomBearerTokenCondition` objects, which define
1069
+ * the conditions under which a Bearer token should be included in the `Authorization` header
1070
+ * of outgoing HTTP requests. Each condition provides a `shouldAddToken` function that dynamically
1071
+ * determines whether the token should be added based on the request, handler, and Keycloak state.
1072
+ */
1073
+ declare const CUSTOM_BEARER_TOKEN_INTERCEPTOR_CONFIG: InjectionToken<CustomBearerTokenCondition[]>;
1074
+ /**
1075
+ * Custom HTTP Interceptor for dynamically adding a Bearer token to requests based on conditions.
1076
+ *
1077
+ * This interceptor uses a flexible approach where the decision to include a Bearer token in the
1078
+ * `Authorization` HTTP header is determined by a user-provided function (`shouldAddToken`).
1079
+ * This enables a dynamic and granular control over when tokens are added to HTTP requests.
1080
+ *
1081
+ * ### Key Features:
1082
+ * 1. **Dynamic Token Inclusion**: Uses a condition function (`shouldAddToken`) to decide dynamically
1083
+ * whether to add the token based on the request, Keycloak state, and other factors.
1084
+ * 2. **Token Management**: Optionally refreshes the Keycloak token before adding it to the request.
1085
+ * 3. **Controlled Authorization**: Adds the Bearer token only when the condition function allows
1086
+ * and the user is authenticated in Keycloak.
1087
+ *
1088
+ * ### Configuration:
1089
+ * The interceptor relies on `CUSTOM_BEARER_TOKEN_INTERCEPTOR_CONFIG`, an injection token that contains
1090
+ * an array of `CustomBearerTokenCondition` objects. Each condition specifies a `shouldAddToken` function
1091
+ * that determines whether to add the Bearer token for a given request.
1092
+ *
1093
+ * ### Workflow:
1094
+ * 1. Reads the conditions from the `CUSTOM_BEARER_TOKEN_INTERCEPTOR_CONFIG` injection token.
1095
+ * 2. Iterates through the conditions and evaluates the `shouldAddToken` function for the request.
1096
+ * 3. If a condition matches:
1097
+ * - Optionally refreshes the Keycloak token if needed.
1098
+ * - Adds the Bearer token to the request's `Authorization` header if the user is authenticated.
1099
+ * 4. If no conditions match, the request proceeds unchanged.
1100
+ *
1101
+ * ### Parameters:
1102
+ * @param req - The `HttpRequest` object representing the outgoing HTTP request.
1103
+ * @param next - The `HttpHandlerFn` for passing the request to the next handler in the chain.
1104
+ *
1105
+ * @returns An `Observable<HttpEvent<unknown>>` representing the HTTP response.
1106
+ *
1107
+ * ### Usage Example:
1108
+ * ```typescript
1109
+ * // Define a custom condition to include the token
1110
+ * const customCondition: CustomBearerTokenCondition = {
1111
+ * shouldAddToken: async (req, next, keycloak) => {
1112
+ * // Add token only for requests to the /api endpoint
1113
+ * return req.url.startsWith('/api') && keycloak.authenticated;
1114
+ * },
1115
+ * };
1116
+ *
1117
+ * // Configure the interceptor with the custom condition
1118
+ * export const appConfig: ApplicationConfig = {
1119
+ * providers: [
1120
+ * provideHttpClient(withInterceptors([customBearerTokenInterceptor])),
1121
+ * {
1122
+ * provide: CUSTOM_BEARER_TOKEN_INTERCEPTOR_CONFIG,
1123
+ * useValue: [customCondition],
1124
+ * },
1125
+ * ],
1126
+ * };
1127
+ * ```
1128
+ */
1129
+ declare const customBearerTokenInterceptor: (req: HttpRequest<unknown>, next: HttpHandlerFn) => Observable<HttpEvent<unknown>>;
1130
+
1131
+ /**
1132
+ * @license
1133
+ * Copyright Mauricio Gemelli Vigolo All Rights Reserved.
1134
+ *
1135
+ * Use of this source code is governed by a MIT-style license that can be
1136
+ * found in the LICENSE file at https://github.com/mauriciovigolo/keycloak-angular/blob/main/LICENSE.md
1137
+ */
1138
+
1139
+ /**
1140
+ * Defines the conditions for including the Bearer token in the Authorization HTTP header.
1141
+ */
1142
+ type IncludeBearerTokenCondition = Partial<BearerTokenCondition> & {
1143
+ /**
1144
+ * A URL pattern (as a `RegExp`) used to determine whether the Bearer token should be added
1145
+ * to the Authorization HTTP header for a given request. The Bearer token is only added if
1146
+ * this pattern matches the request's URL.
1147
+ *
1148
+ * This EXPLICIT configuration is for security purposes, ensuring that internal tokens are not
1149
+ * shared with unintended services.
1150
+ */
1151
+ urlPattern: RegExp;
1152
+ /**
1153
+ * An optional array of HTTP methods (`HttpMethod[]`) to further refine the conditions under
1154
+ * which the Bearer token is added. If not provided, the default behavior is to add the token
1155
+ * for all HTTP methods matching the `urlPattern`.
1156
+ */
1157
+ httpMethods?: HttpMethod[];
1158
+ };
1159
+ /**
1160
+ * Injection token for configuring the `includeBearerTokenInterceptor`, allowing the specification
1161
+ * of conditions under which the Bearer token should be included in HTTP request headers.
1162
+ *
1163
+ * This configuration supports multiple conditions, enabling customization for different URLs.
1164
+ * It also provides options to tailor the Bearer prefix and the Authorization header name as needed.
1165
+ */
1166
+ declare const INCLUDE_BEARER_TOKEN_INTERCEPTOR_CONFIG: InjectionToken<IncludeBearerTokenCondition[]>;
1167
+ /**
1168
+ * HTTP Interceptor to include a Bearer token in the Authorization header for specific HTTP requests.
1169
+ *
1170
+ * This interceptor ensures that a Bearer token is added to outgoing HTTP requests based on explicitly
1171
+ * defined conditions. By default, the interceptor does not include the Bearer token unless the request
1172
+ * matches the provided configuration (`IncludeBearerTokenCondition`). This approach enhances security
1173
+ * by preventing sensitive tokens from being unintentionally sent to unauthorized services.
1174
+ *
1175
+ * ### Features:
1176
+ * 1. **Explicit URL Matching**: The interceptor uses regular expressions to match URLs where the Bearer token should be included.
1177
+ * 2. **HTTP Method Filtering**: Optional filtering by HTTP methods (e.g., `GET`, `POST`, `PUT`) to refine the conditions for adding the token.
1178
+ * 3. **Token Management**: Ensures the Keycloak token is valid by optionally refreshing it before attaching it to the request.
1179
+ * 4. **Controlled Authorization**: Sends the token only for requests where the user is authenticated, and the conditions match.
1180
+ *
1181
+ * ### Workflow:
1182
+ * - Reads conditions from `INCLUDE_BEARER_TOKEN_INTERCEPTOR_CONFIG`, which specifies when the Bearer token should be included.
1183
+ * - If a request matches the conditions:
1184
+ * 1. The Keycloak token is refreshed if needed.
1185
+ * 2. The Bearer token is added to the Authorization header.
1186
+ * 3. The modified request is passed to the next handler.
1187
+ * - If no conditions match, the request proceeds unchanged.
1188
+ *
1189
+ * ### Security:
1190
+ * By explicitly defining URL patterns and optional HTTP methods, this interceptor prevents the leakage of tokens
1191
+ * to unintended endpoints, such as third-party APIs or external services. This is especially critical for applications
1192
+ * that interact with both internal and external services.
1193
+ *
1194
+ * @param req - The `HttpRequest` object representing the outgoing HTTP request.
1195
+ * @param next - The `HttpHandlerFn` for passing the request to the next handler in the chain.
1196
+ * @returns An `Observable<HttpEvent<unknown>>` representing the asynchronous HTTP response.
1197
+ *
1198
+ * ### Configuration:
1199
+ * The interceptor relies on `INCLUDE_BEARER_TOKEN_INTERCEPTOR_CONFIG`, an injection token that holds
1200
+ * an array of `IncludeBearerTokenCondition` objects. Each object defines the conditions for including
1201
+ * the Bearer token in the request.
1202
+ *
1203
+ * #### Example Configuration:
1204
+ * ```typescript
1205
+ * provideHttpClient(
1206
+ * withInterceptors([includeBearerTokenInterceptor]),
1207
+ * {
1208
+ * provide: INCLUDE_BEARER_TOKEN_INTERCEPTOR_CONFIG,
1209
+ * useValue: [
1210
+ * {
1211
+ * urlPattern: /^https:\/\/api\.internal\.myapp\.com\/.*\/,
1212
+ * httpMethods: ['GET', 'POST'], // Add the token only for GET and POST methods
1213
+ * },
1214
+ * ],
1215
+ * }
1216
+ * );
1217
+ * ```
1218
+ *
1219
+ * ### Example Usage:
1220
+ * ```typescript
1221
+ * export const appConfig: ApplicationConfig = {
1222
+ * providers: [
1223
+ * provideHttpClient(withInterceptors([includeBearerTokenInterceptor])),
1224
+ * provideZoneChangeDetection({ eventCoalescing: true }),
1225
+ * provideRouter(routes),
1226
+ * ],
1227
+ * };
1228
+ * ```
1229
+ *
1230
+ * ### Example Matching Condition:
1231
+ * ```typescript
1232
+ * {
1233
+ * urlPattern: /^(https:\/\/internal\.mycompany\.com)(\/.*)?$/i,
1234
+ * httpMethods: ['GET', 'PUT'], // Optional: Match only specific HTTP methods
1235
+ * }
1236
+ * ```
1237
+ */
1238
+ declare const includeBearerTokenInterceptor: (req: HttpRequest<unknown>, next: HttpHandlerFn) => Observable<HttpEvent<unknown>>;
1239
+
1240
+ /**
1241
+ * Service to monitor user activity in an Angular application.
1242
+ * Tracks user interactions (e.g., mouse movement, touch, key presses, clicks, and scrolls)
1243
+ * and updates the last activity timestamp. Consumers can check for user inactivity
1244
+ * based on a configurable timeout.
1245
+ *
1246
+ * The service is supposed to be used in the client context and for safety, it checks during the startup
1247
+ * if it is a browser context.
1248
+ */
1249
+ declare class UserActivityService implements OnDestroy {
1250
+ private ngZone;
1251
+ /**
1252
+ * Signal to store the timestamp of the last user activity.
1253
+ * The timestamp is represented as the number of milliseconds since epoch.
1254
+ */
1255
+ private lastActivity;
1256
+ /**
1257
+ * Subject to signal the destruction of the service.
1258
+ * Used to clean up RxJS subscriptions.
1259
+ */
1260
+ private destroy$;
1261
+ /**
1262
+ * Computed signal to expose the last user activity as a read-only signal.
1263
+ */
1264
+ readonly lastActivitySignal: i0.Signal<number>;
1265
+ /**
1266
+ * Starts monitoring user activity events (`mousemove`, `touchstart`, `keydown`, `click`, `scroll`)
1267
+ * and updates the last activity timestamp using RxJS with debounce.
1268
+ * The events are processed outside Angular zone for performance optimization.
1269
+ */
1270
+ startMonitoring(): void;
1271
+ /**
1272
+ * Updates the last activity timestamp to the current time.
1273
+ * This method runs inside Angular's zone to ensure reactivity with Angular signals.
1274
+ */
1275
+ private updateLastActivity;
1276
+ /**
1277
+ * Retrieves the timestamp of the last recorded user activity.
1278
+ * @returns {number} The last activity timestamp in milliseconds since epoch.
1279
+ */
1280
+ get lastActivityTime(): number;
1281
+ /**
1282
+ * Determines whether the user interacted with the application, meaning it is activily using the application, based on
1283
+ * the specified duration.
1284
+ * @param timeout - The inactivity timeout in milliseconds.
1285
+ * @returns {boolean} `true` if the user is inactive, otherwise `false`.
1286
+ */
1287
+ isActive(timeout: number): boolean;
1288
+ /**
1289
+ * Cleans up RxJS subscriptions and resources when the service is destroyed.
1290
+ * This method is automatically called by Angular when the service is removed.
1291
+ */
1292
+ ngOnDestroy(): void;
1293
+ static ɵfac: i0.ɵɵFactoryDeclaration<UserActivityService, never>;
1294
+ static ɵprov: i0.ɵɵInjectableDeclaration<UserActivityService>;
1295
+ }
1296
+
1297
+ /**
1298
+ * Configuration options for the `AutoRefreshTokenService`.
1299
+ */
1300
+ type AutoRefreshTokenOptions = {
1301
+ /**
1302
+ * Maximum allowed inactivity duration in milliseconds before
1303
+ * the session times out. Default is `300000`.
1304
+ */
1305
+ sessionTimeout?: number;
1306
+ /**
1307
+ * Action to take when the session times out due to inactivity.
1308
+ * Options are:
1309
+ * - `'login'`: Redirect to the Keycloak login page.
1310
+ * - `'logout'`: Log the user out of the session.
1311
+ * - `'none'`: Do nothing.
1312
+ * Default is `'logout'`.
1313
+ */
1314
+ onInactivityTimeout?: 'login' | 'logout' | 'none';
1315
+ /**
1316
+ * Logout options to pass to keycloak.logout when the user is getting logged out automatically after timout.
1317
+ *
1318
+ * Default value: undefined
1319
+ */
1320
+ logoutOptions?: KeycloakLogoutOptions;
1321
+ /**
1322
+ * Login options to pass to keycloak.login when the user is getting logged in automatically after timeout.
1323
+ *
1324
+ * Default value: undefined
1325
+ */
1326
+ loginOptions?: KeycloakLoginOptions;
1327
+ };
1328
+ /**
1329
+ * Service to automatically manage the Keycloak token refresh process
1330
+ * based on user activity and token expiration events. This service
1331
+ * integrates with Keycloak for session management and interacts with
1332
+ * user activity monitoring to determine the appropriate action when
1333
+ * the token expires.
1334
+ *
1335
+ * The service listens to `KeycloakSignal` for token-related events
1336
+ * (e.g., `TokenExpired`) and provides configurable options for
1337
+ * session timeout and inactivity handling.
1338
+ */
1339
+ declare class AutoRefreshTokenService {
1340
+ private readonly keycloak;
1341
+ private readonly userActivity;
1342
+ private options;
1343
+ private initialized;
1344
+ constructor();
1345
+ private get defaultOptions();
1346
+ private executeOnInactivityTimeout;
1347
+ private processTokenExpiredEvent;
1348
+ start(options?: AutoRefreshTokenOptions): void;
1349
+ static ɵfac: i0.ɵɵFactoryDeclaration<AutoRefreshTokenService, never>;
1350
+ static ɵprov: i0.ɵɵInjectableDeclaration<AutoRefreshTokenService>;
1351
+ }
1352
+
1353
+ /**
1354
+ * Keycloak event types, as described at the keycloak-js documentation:
1355
+ * https://www.keycloak.org/docs/latest/securing_apps/index.html#callback-events
1356
+ */
1357
+ declare enum KeycloakEventType {
1358
+ /**
1359
+ * Keycloak Angular is not initialized yet. This is the initial state applied to the Keycloak Event Signal.
1360
+ * Note: This event is only emitted in Keycloak Angular, it is not part of the keycloak-js.
1361
+ */
1362
+ KeycloakAngularNotInitialized = "KeycloakAngularNotInitialized",
1363
+ /**
1364
+ * Keycloak Angular is in the process of initializing the providers and Keycloak Instance.
1365
+ * Note: This event is only emitted in Keycloak Angular, it is not part of the keycloak-js.
1366
+ */
1367
+ KeycloakAngularInit = "KeycloakAngularInit",
1368
+ /**
1369
+ * Triggered if there is an error during authentication.
1370
+ */
1371
+ AuthError = "AuthError",
1372
+ /**
1373
+ * Triggered when the user logs out. This event will only be triggered
1374
+ * if the session status iframe is enabled or in Cordova mode.
1375
+ */
1376
+ AuthLogout = "AuthLogout",
1377
+ /**
1378
+ * Triggered if an error occurs while attempting to refresh the token.
1379
+ */
1380
+ AuthRefreshError = "AuthRefreshError",
1381
+ /**
1382
+ * Triggered when the token is successfully refreshed.
1383
+ */
1384
+ AuthRefreshSuccess = "AuthRefreshSuccess",
1385
+ /**
1386
+ * Triggered when a user is successfully authenticated.
1387
+ */
1388
+ AuthSuccess = "AuthSuccess",
1389
+ /**
1390
+ * Triggered when the Keycloak adapter has completed initialization.
1391
+ */
1392
+ Ready = "Ready",
1393
+ /**
1394
+ * Triggered when the access token expires. Depending on the flow, you may
1395
+ * need to use `updateToken` to refresh the token or redirect the user
1396
+ * to the login screen.
1397
+ */
1398
+ TokenExpired = "TokenExpired",
1399
+ /**
1400
+ * Triggered when an authentication action is requested by the application.
1401
+ */
1402
+ ActionUpdate = "ActionUpdate"
1403
+ }
1404
+ /**
1405
+ * Arguments for the `Ready` event, representing the authentication state.
1406
+ */
1407
+ type ReadyArgs = boolean;
1408
+ /**
1409
+ * Arguments for the `ActionUpdate` event, providing information about the status
1410
+ * and optional details about the action.
1411
+ */
1412
+ type ActionUpdateArgs = {
1413
+ /**
1414
+ * Status of the action, indicating whether it was successful, encountered an error,
1415
+ * or was cancelled.
1416
+ */
1417
+ status: 'success' | 'error' | 'cancelled';
1418
+ /**
1419
+ * Optional name or identifier of the action performed.
1420
+ */
1421
+ action?: string;
1422
+ };
1423
+ /**
1424
+ * Arguments for the `AuthError` event, providing detailed error information.
1425
+ */
1426
+ type AuthErrorArgs = KeycloakError;
1427
+ type EventArgs = ReadyArgs | ActionUpdateArgs | AuthErrorArgs;
1428
+ /**
1429
+ * Helper function to typecast unknown arguments into a specific Keycloak event type.
1430
+ *
1431
+ * @template T - The expected argument type.
1432
+ * @param args - The arguments to be cast.
1433
+ * @returns The arguments typed as `T`.
1434
+ */
1435
+ declare const typeEventArgs: <T extends EventArgs>(args: unknown) => T;
1436
+ /**
1437
+ * Structure of a Keycloak event, including its type and optional arguments.
1438
+ */
1439
+ interface KeycloakEvent {
1440
+ /**
1441
+ * Event type as described at {@link KeycloakEventType}.
1442
+ */
1443
+ type: KeycloakEventType;
1444
+ /**
1445
+ * Arguments from the keycloak-js event function.
1446
+ */
1447
+ args?: unknown;
1448
+ }
1449
+ /**
1450
+ * Creates a signal to manage Keycloak events, initializing the signal with
1451
+ * appropriate default values or values from a given Keycloak instance.
1452
+ *
1453
+ * @param keycloak - An instance of the Keycloak client.
1454
+ * @returns A `Signal` that tracks the current Keycloak event state.
1455
+ */
1456
+ declare const createKeycloakSignal: (keycloak?: Keycloak__default) => i0.WritableSignal<KeycloakEvent>;
1457
+ /**
1458
+ * Injection token for the Keycloak events signal, used for dependency injection.
1459
+ */
1460
+ declare const KEYCLOAK_EVENT_SIGNAL: InjectionToken<Signal<KeycloakEvent>>;
1461
+
1462
+ /**
1463
+ * @license
1464
+ * Copyright Mauricio Gemelli Vigolo All Rights Reserved.
1465
+ *
1466
+ * Use of this source code is governed by a MIT-style license that can be
1467
+ * found in the LICENSE file at https://github.com/mauriciovigolo/keycloak-angular/blob/main/LICENSE.md
1468
+ */
1469
+
1470
+ /**
1471
+ * Options for configuring Keycloak and additional providers.
1472
+ */
1473
+ type ProvideKeycloakOptions = {
1474
+ /**
1475
+ * Keycloak configuration, including the server URL, realm, and client ID.
1476
+ */
1477
+ config: KeycloakConfig;
1478
+ /**
1479
+ * Optional initialization options for the Keycloak instance.
1480
+ * If not provided, Keycloak will not initialize automatically.
1481
+ */
1482
+ initOptions?: KeycloakInitOptions;
1483
+ /**
1484
+ * Optional array of additional Angular providers or environment providers.
1485
+ */
1486
+ providers?: Array<Provider | EnvironmentProviders>;
1487
+ /**
1488
+ * Optional array of Keycloak features to extend the functionality of the Keycloak integration.
1489
+ */
1490
+ features?: Array<KeycloakFeature>;
1491
+ };
1492
+ /**
1493
+ * Configures and provides Keycloak as a dependency in an Angular application.
1494
+ *
1495
+ * This function initializes a Keycloak instance with the provided configuration and
1496
+ * optional initialization options. It integrates Keycloak into Angular dependency
1497
+ * injection system, allowing easy consumption throughout the application. Additionally,
1498
+ * it supports custom providers and Keycloak Angular features.
1499
+ *
1500
+ * If `initOptions` is not provided, the Keycloak instance will not be automatically initialized.
1501
+ * In such cases, the application must call `keycloak.init()` explicitly.
1502
+ *
1503
+ * @param options - Configuration object for Keycloak:
1504
+ * - `config`: The Keycloak configuration, including the server URL, realm, and client ID.
1505
+ * - `initOptions` (Optional): Initialization options for the Keycloak instance.
1506
+ * - `providers` (Optional): Additional Angular providers to include.
1507
+ * - `features` (Optional): Keycloak Angular features to configure during initialization.
1508
+ *
1509
+ * @returns An `EnvironmentProviders` object integrating Keycloak setup and additional providers.
1510
+ *
1511
+ * @example
1512
+ * ```ts
1513
+ * import { provideKeycloak } from './keycloak.providers';
1514
+ * import { bootstrapApplication } from '@angular/platform-browser';
1515
+ * import { AppComponent } from './app/app.component';
1516
+ *
1517
+ * bootstrapApplication(AppComponent, {
1518
+ * providers: [
1519
+ * provideKeycloak({
1520
+ * config: {
1521
+ * url: 'https://auth-server.example.com',
1522
+ * realm: 'my-realm',
1523
+ * clientId: 'my-client',
1524
+ * },
1525
+ * initOptions: {
1526
+ * onLoad: 'login-required',
1527
+ * },
1528
+ * }),
1529
+ * ],
1530
+ * });
1531
+ * ```
1532
+ */
1533
+ declare function provideKeycloak(options: ProvideKeycloakOptions): EnvironmentProviders;
1534
+
1535
+ export { AutoRefreshTokenService, CUSTOM_BEARER_TOKEN_INTERCEPTOR_CONFIG, CoreModule, HasRolesDirective, INCLUDE_BEARER_TOKEN_INTERCEPTOR_CONFIG, KEYCLOAK_EVENT_SIGNAL, KeycloakAngularModule, KeycloakAuthGuard, KeycloakBearerInterceptor, KeycloakEventType, KeycloakEventTypeLegacy, KeycloakService, UserActivityService, addAuthorizationHeader, conditionallyUpdateToken, createAuthGuard, createInterceptorCondition, createKeycloakSignal, customBearerTokenInterceptor, includeBearerTokenInterceptor, provideKeycloak, typeEventArgs, withAutoRefreshToken };
1536
+ export type { ActionUpdateArgs, AuthErrorArgs, AuthGuardData, BearerTokenCondition, CustomBearerTokenCondition, HttpMethod, IncludeBearerTokenCondition, KeycloakEvent, KeycloakEventLegacy, KeycloakFeature, KeycloakOptions, ProvideKeycloakOptions, ReadyArgs, Roles };