keycloak-angular 16.1.0 → 19.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.
Files changed (39) hide show
  1. package/README.md +244 -150
  2. package/fesm2022/keycloak-angular.mjs +1324 -51
  3. package/fesm2022/keycloak-angular.mjs.map +1 -1
  4. package/index.d.ts +3 -0
  5. package/lib/directives/has-roles.directive.d.ts +95 -0
  6. package/lib/features/keycloak.feature.d.ts +43 -0
  7. package/lib/features/with-refresh-token.feature.d.ts +66 -0
  8. package/lib/guards/auth.guard.d.ts +75 -0
  9. package/lib/interceptors/custom-bearer-token.interceptor.d.ts +97 -0
  10. package/lib/interceptors/include-bearer-token.interceptor.d.ts +111 -0
  11. package/lib/interceptors/keycloak.interceptor.d.ts +71 -0
  12. package/lib/{core → legacy/core}/core.module.d.ts +5 -0
  13. package/lib/legacy/core/interceptors/keycloak-bearer.interceptor.d.ts +53 -0
  14. package/lib/legacy/core/interfaces/keycloak-event.d.ts +74 -0
  15. package/lib/legacy/core/interfaces/keycloak-options.d.ts +146 -0
  16. package/lib/legacy/core/services/keycloak-auth-guard.d.ts +50 -0
  17. package/lib/legacy/core/services/keycloak.service.d.ts +316 -0
  18. package/lib/{keycloak-angular.module.d.ts → legacy/keycloak-angular.module.d.ts} +5 -0
  19. package/lib/legacy/public_api.d.ts +14 -0
  20. package/lib/provide-keycloak.d.ts +74 -0
  21. package/lib/services/auto-refresh-token.service.d.ts +47 -0
  22. package/lib/services/user-activity.service.d.ts +66 -0
  23. package/lib/signals/keycloak-events-signal.d.ts +118 -0
  24. package/package.json +4 -6
  25. package/public_api.d.ts +19 -7
  26. package/esm2022/keycloak-angular.mjs +0 -2
  27. package/esm2022/lib/core/core.module.mjs +0 -33
  28. package/esm2022/lib/core/interceptors/keycloak-bearer.interceptor.mjs +0 -51
  29. package/esm2022/lib/core/interfaces/keycloak-event.mjs +0 -12
  30. package/esm2022/lib/core/interfaces/keycloak-options.mjs +0 -2
  31. package/esm2022/lib/core/services/keycloak-auth-guard.mjs +0 -17
  32. package/esm2022/lib/core/services/keycloak.service.mjs +0 -204
  33. package/esm2022/lib/keycloak-angular.module.mjs +0 -15
  34. package/esm2022/public_api.mjs +0 -7
  35. package/lib/core/interceptors/keycloak-bearer.interceptor.d.ts +0 -14
  36. package/lib/core/interfaces/keycloak-event.d.ts +0 -14
  37. package/lib/core/interfaces/keycloak-options.d.ts +0 -22
  38. package/lib/core/services/keycloak-auth-guard.d.ts +0 -11
  39. package/lib/core/services/keycloak.service.d.ts +0 -42
@@ -0,0 +1,75 @@
1
+ /**
2
+ * @license
3
+ * Copyright Mauricio Gemelli Vigolo All Rights Reserved.
4
+ *
5
+ * Use of this source code is governed by a MIT-style license that can be
6
+ * found in the LICENSE file at https://github.com/mauriciovigolo/keycloak-angular/blob/main/LICENSE.md
7
+ */
8
+ import Keycloak from 'keycloak-js';
9
+ import { ActivatedRouteSnapshot, CanActivateChildFn, CanActivateFn, RouterStateSnapshot, UrlTree } from '@angular/router';
10
+ /**
11
+ * Type representing the roles granted to a user, including both realm and resource-level roles.
12
+ */
13
+ type Roles = {
14
+ /**
15
+ * Roles assigned at the realm level.
16
+ */
17
+ realmRoles: string[];
18
+ /**
19
+ * Roles assigned at the resource level, organized by resource name.
20
+ */
21
+ resourceRoles: {
22
+ [resource: string]: string[];
23
+ };
24
+ };
25
+ /**
26
+ * Data structure passed to the custom authorization guard to determine access.
27
+ */
28
+ export type AuthGuardData = {
29
+ /**
30
+ * Indicates whether the user is currently authenticated.
31
+ */
32
+ authenticated: boolean;
33
+ /**
34
+ * A collection of roles granted to the user, including both realm and resource roles.
35
+ */
36
+ grantedRoles: Roles;
37
+ /**
38
+ * The Keycloak instance managing the user's session and access.
39
+ */
40
+ keycloak: Keycloak;
41
+ };
42
+ /**
43
+ * Creates a custom authorization guard for Angular routes, enabling fine-grained access control.
44
+ *
45
+ * This guard invokes the provided `isAccessAllowed` function to determine if access is permitted
46
+ * based on the current route, router state, and user's authentication and roles data.
47
+ *
48
+ * @template T - The type of the guard function (`CanActivateFn` or `CanActivateChildFn`).
49
+ * @param isAccessAllowed - A callback function that evaluates access conditions. The function receives:
50
+ * - `route`: The current `ActivatedRouteSnapshot` for the route being accessed.
51
+ * - `state`: The current `RouterStateSnapshot` representing the router's state.
52
+ * - `authData`: An `AuthGuardData` object containing the user's authentication status, roles, and Keycloak instance.
53
+ * @returns A guard function of type `T` that can be used as a route `canActivate` or `canActivateChild` guard.
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * import { createAuthGuard } from './auth-guard';
58
+ * import { Routes } from '@angular/router';
59
+ *
60
+ * const isUserAllowed = async (route, state, authData) => {
61
+ * const { authenticated, grantedRoles } = authData;
62
+ * return authenticated && grantedRoles.realmRoles.includes('admin');
63
+ * };
64
+ *
65
+ * const routes: Routes = [
66
+ * {
67
+ * path: 'admin',
68
+ * canActivate: [createAuthGuard(isUserAllowed)],
69
+ * component: AdminComponent,
70
+ * },
71
+ * ];
72
+ * ```
73
+ */
74
+ export declare const createAuthGuard: <T extends CanActivateFn | CanActivateChildFn>(isAccessAllowed: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot, authData: AuthGuardData) => Promise<boolean | UrlTree>) => T;
75
+ export {};
@@ -0,0 +1,97 @@
1
+ /**
2
+ * @license
3
+ * Copyright Mauricio Gemelli Vigolo All Rights Reserved.
4
+ *
5
+ * Use of this source code is governed by a MIT-style license that can be
6
+ * found in the LICENSE file at https://github.com/mauriciovigolo/keycloak-angular/blob/main/LICENSE.md
7
+ */
8
+ import Keycloak from 'keycloak-js';
9
+ import { Observable } from 'rxjs';
10
+ import { InjectionToken } from '@angular/core';
11
+ import { HttpEvent, HttpHandlerFn, HttpRequest } from '@angular/common/http';
12
+ import { BearerTokenCondition } from './keycloak.interceptor';
13
+ /**
14
+ * Defines a custom condition for determining whether a Bearer token should be included
15
+ * in the `Authorization` header of an outgoing HTTP request.
16
+ *
17
+ * This type extends the `BearerTokenCondition` type and adds a dynamic function
18
+ * (`shouldAddToken`) that evaluates whether the token should be added based on the
19
+ * request, handler, and Keycloak state.
20
+ */
21
+ export type CustomBearerTokenCondition = Partial<BearerTokenCondition> & {
22
+ /**
23
+ * A function that dynamically determines whether the Bearer token should be included
24
+ * in the `Authorization` header for a given request.
25
+ *
26
+ * This function is asynchronous and receives the following arguments:
27
+ * - `req`: The `HttpRequest` object representing the current outgoing HTTP request.
28
+ * - `next`: The `HttpHandlerFn` for forwarding the request to the next handler in the chain.
29
+ * - `keycloak`: The `Keycloak` instance representing the authentication context.
30
+ */
31
+ shouldAddToken: (req: HttpRequest<unknown>, next: HttpHandlerFn, keycloak: Keycloak) => Promise<boolean>;
32
+ };
33
+ /**
34
+ * Injection token for configuring the `customBearerTokenInterceptor`.
35
+ *
36
+ * This injection token holds an array of `CustomBearerTokenCondition` objects, which define
37
+ * the conditions under which a Bearer token should be included in the `Authorization` header
38
+ * of outgoing HTTP requests. Each condition provides a `shouldAddToken` function that dynamically
39
+ * determines whether the token should be added based on the request, handler, and Keycloak state.
40
+ */
41
+ export declare const CUSTOM_BEARER_TOKEN_INTERCEPTOR_CONFIG: InjectionToken<CustomBearerTokenCondition[]>;
42
+ /**
43
+ * Custom HTTP Interceptor for dynamically adding a Bearer token to requests based on conditions.
44
+ *
45
+ * This interceptor uses a flexible approach where the decision to include a Bearer token in the
46
+ * `Authorization` HTTP header is determined by a user-provided function (`shouldAddToken`).
47
+ * This enables a dynamic and granular control over when tokens are added to HTTP requests.
48
+ *
49
+ * ### Key Features:
50
+ * 1. **Dynamic Token Inclusion**: Uses a condition function (`shouldAddToken`) to decide dynamically
51
+ * whether to add the token based on the request, Keycloak state, and other factors.
52
+ * 2. **Token Management**: Optionally refreshes the Keycloak token before adding it to the request.
53
+ * 3. **Controlled Authorization**: Adds the Bearer token only when the condition function allows
54
+ * and the user is authenticated in Keycloak.
55
+ *
56
+ * ### Configuration:
57
+ * The interceptor relies on `CUSTOM_BEARER_TOKEN_INTERCEPTOR_CONFIG`, an injection token that contains
58
+ * an array of `CustomBearerTokenCondition` objects. Each condition specifies a `shouldAddToken` function
59
+ * that determines whether to add the Bearer token for a given request.
60
+ *
61
+ * ### Workflow:
62
+ * 1. Reads the conditions from the `CUSTOM_BEARER_TOKEN_INTERCEPTOR_CONFIG` injection token.
63
+ * 2. Iterates through the conditions and evaluates the `shouldAddToken` function for the request.
64
+ * 3. If a condition matches:
65
+ * - Optionally refreshes the Keycloak token if needed.
66
+ * - Adds the Bearer token to the request's `Authorization` header if the user is authenticated.
67
+ * 4. If no conditions match, the request proceeds unchanged.
68
+ *
69
+ * ### Parameters:
70
+ * @param req - The `HttpRequest` object representing the outgoing HTTP request.
71
+ * @param next - The `HttpHandlerFn` for passing the request to the next handler in the chain.
72
+ *
73
+ * @returns An `Observable<HttpEvent<unknown>>` representing the HTTP response.
74
+ *
75
+ * ### Usage Example:
76
+ * ```typescript
77
+ * // Define a custom condition to include the token
78
+ * const customCondition: CustomBearerTokenCondition = {
79
+ * shouldAddToken: async (req, next, keycloak) => {
80
+ * // Add token only for requests to the /api endpoint
81
+ * return req.url.startsWith('/api') && keycloak.authenticated;
82
+ * },
83
+ * };
84
+ *
85
+ * // Configure the interceptor with the custom condition
86
+ * export const appConfig: ApplicationConfig = {
87
+ * providers: [
88
+ * provideHttpClient(withInterceptors([customBearerTokenInterceptor])),
89
+ * {
90
+ * provide: CUSTOM_BEARER_TOKEN_INTERCEPTOR_CONFIG,
91
+ * useValue: [customCondition],
92
+ * },
93
+ * ],
94
+ * };
95
+ * ```
96
+ */
97
+ export declare const customBearerTokenInterceptor: (req: HttpRequest<unknown>, next: HttpHandlerFn) => Observable<HttpEvent<unknown>>;
@@ -0,0 +1,111 @@
1
+ /**
2
+ * @license
3
+ * Copyright Mauricio Gemelli Vigolo All Rights Reserved.
4
+ *
5
+ * Use of this source code is governed by a MIT-style license that can be
6
+ * found in the LICENSE file at https://github.com/mauriciovigolo/keycloak-angular/blob/main/LICENSE.md
7
+ */
8
+ import { Observable } from 'rxjs';
9
+ import { InjectionToken } from '@angular/core';
10
+ import { HttpEvent, HttpHandlerFn, HttpRequest } from '@angular/common/http';
11
+ import { HttpMethod, BearerTokenCondition } from './keycloak.interceptor';
12
+ /**
13
+ * Defines the conditions for including the Bearer token in the Authorization HTTP header.
14
+ */
15
+ export type IncludeBearerTokenCondition = Partial<BearerTokenCondition> & {
16
+ /**
17
+ * A URL pattern (as a `RegExp`) used to determine whether the Bearer token should be added
18
+ * to the Authorization HTTP header for a given request. The Bearer token is only added if
19
+ * this pattern matches the request's URL.
20
+ *
21
+ * This EXPLICIT configuration is for security purposes, ensuring that internal tokens are not
22
+ * shared with unintended services.
23
+ */
24
+ urlPattern: RegExp;
25
+ /**
26
+ * An optional array of HTTP methods (`HttpMethod[]`) to further refine the conditions under
27
+ * which the Bearer token is added. If not provided, the default behavior is to add the token
28
+ * for all HTTP methods matching the `urlPattern`.
29
+ */
30
+ httpMethods?: HttpMethod[];
31
+ };
32
+ /**
33
+ * Injection token for configuring the `includeBearerTokenInterceptor`, allowing the specification
34
+ * of conditions under which the Bearer token should be included in HTTP request headers.
35
+ *
36
+ * This configuration supports multiple conditions, enabling customization for different URLs.
37
+ * It also provides options to tailor the Bearer prefix and the Authorization header name as needed.
38
+ */
39
+ export declare const INCLUDE_BEARER_TOKEN_INTERCEPTOR_CONFIG: InjectionToken<IncludeBearerTokenCondition[]>;
40
+ /**
41
+ * HTTP Interceptor to include a Bearer token in the Authorization header for specific HTTP requests.
42
+ *
43
+ * This interceptor ensures that a Bearer token is added to outgoing HTTP requests based on explicitly
44
+ * defined conditions. By default, the interceptor does not include the Bearer token unless the request
45
+ * matches the provided configuration (`IncludeBearerTokenCondition`). This approach enhances security
46
+ * by preventing sensitive tokens from being unintentionally sent to unauthorized services.
47
+ *
48
+ * ### Features:
49
+ * 1. **Explicit URL Matching**: The interceptor uses regular expressions to match URLs where the Bearer token should be included.
50
+ * 2. **HTTP Method Filtering**: Optional filtering by HTTP methods (e.g., `GET`, `POST`, `PUT`) to refine the conditions for adding the token.
51
+ * 3. **Token Management**: Ensures the Keycloak token is valid by optionally refreshing it before attaching it to the request.
52
+ * 4. **Controlled Authorization**: Sends the token only for requests where the user is authenticated, and the conditions match.
53
+ *
54
+ * ### Workflow:
55
+ * - Reads conditions from `INCLUDE_BEARER_TOKEN_INTERCEPTOR_CONFIG`, which specifies when the Bearer token should be included.
56
+ * - If a request matches the conditions:
57
+ * 1. The Keycloak token is refreshed if needed.
58
+ * 2. The Bearer token is added to the Authorization header.
59
+ * 3. The modified request is passed to the next handler.
60
+ * - If no conditions match, the request proceeds unchanged.
61
+ *
62
+ * ### Security:
63
+ * By explicitly defining URL patterns and optional HTTP methods, this interceptor prevents the leakage of tokens
64
+ * to unintended endpoints, such as third-party APIs or external services. This is especially critical for applications
65
+ * that interact with both internal and external services.
66
+ *
67
+ * @param req - The `HttpRequest` object representing the outgoing HTTP request.
68
+ * @param next - The `HttpHandlerFn` for passing the request to the next handler in the chain.
69
+ * @returns An `Observable<HttpEvent<unknown>>` representing the asynchronous HTTP response.
70
+ *
71
+ * ### Configuration:
72
+ * The interceptor relies on `INCLUDE_BEARER_TOKEN_INTERCEPTOR_CONFIG`, an injection token that holds
73
+ * an array of `IncludeBearerTokenCondition` objects. Each object defines the conditions for including
74
+ * the Bearer token in the request.
75
+ *
76
+ * #### Example Configuration:
77
+ * ```typescript
78
+ * provideHttpClient(
79
+ * withInterceptors([includeBearerTokenInterceptor]),
80
+ * {
81
+ * provide: INCLUDE_BEARER_TOKEN_INTERCEPTOR_CONFIG,
82
+ * useValue: [
83
+ * {
84
+ * urlPattern: /^https:\/\/api\.internal\.myapp\.com\/.*\/,
85
+ * httpMethods: ['GET', 'POST'], // Add the token only for GET and POST methods
86
+ * },
87
+ * ],
88
+ * }
89
+ * );
90
+ * ```
91
+ *
92
+ * ### Example Usage:
93
+ * ```typescript
94
+ * export const appConfig: ApplicationConfig = {
95
+ * providers: [
96
+ * provideHttpClient(withInterceptors([includeBearerTokenInterceptor])),
97
+ * provideZoneChangeDetection({ eventCoalescing: true }),
98
+ * provideRouter(routes),
99
+ * ],
100
+ * };
101
+ * ```
102
+ *
103
+ * ### Example Matching Condition:
104
+ * ```typescript
105
+ * {
106
+ * urlPattern: /^(https:\/\/internal\.mycompany\.com)(\/.*)?$/i,
107
+ * httpMethods: ['GET', 'PUT'], // Optional: Match only specific HTTP methods
108
+ * }
109
+ * ```
110
+ */
111
+ export declare const includeBearerTokenInterceptor: (req: HttpRequest<unknown>, next: HttpHandlerFn) => Observable<HttpEvent<unknown>>;
@@ -0,0 +1,71 @@
1
+ /**
2
+ * @license
3
+ * Copyright Mauricio Gemelli Vigolo All Rights Reserved.
4
+ *
5
+ * Use of this source code is governed by a MIT-style license that can be
6
+ * found in the LICENSE file at https://github.com/mauriciovigolo/keycloak-angular/blob/main/LICENSE.md
7
+ */
8
+ import { Observable } from 'rxjs';
9
+ import Keycloak from 'keycloak-js';
10
+ import { HttpEvent, HttpHandlerFn, HttpRequest } from '@angular/common/http';
11
+ /**
12
+ * Represents the HTTP methods supported by the interceptor for authorization purposes.
13
+ */
14
+ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'PATCH';
15
+ /**
16
+ * Common attributes for the Auth Bearer interceptor that can be reused in other interceptor implementations.
17
+ */
18
+ export type BearerTokenCondition = {
19
+ /**
20
+ * Prefix to be used in the Authorization header. Default is "Bearer".
21
+ * This will result in a header formatted as: `Authorization: Bearer <token>`.
22
+ *
23
+ * Adjust this value if your backend expects a different prefix in the Authorization header.
24
+ */
25
+ bearerPrefix?: string;
26
+ /**
27
+ * Name of the HTTP header used for authorization. Default is "Authorization".
28
+ * Customize this value if your backend expects a different header, e.g., "JWT-Authorization".
29
+ */
30
+ authorizationHeaderName?: string;
31
+ /**
32
+ * Function to determine whether the token should be updated before a request. Default is a function returning true.
33
+ * If the function returns `true`, the token's validity will be checked and updated if needed.
34
+ * If it returns `false`, the token update process will be skipped for that request.
35
+ *
36
+ * @param request - The current `HttpRequest` object being intercepted.
37
+ * @returns A boolean indicating whether to update the token.
38
+ */
39
+ shouldUpdateToken?: (request: HttpRequest<unknown>) => boolean;
40
+ };
41
+ /**
42
+ * Generic factory function to create an interceptor condition with default values.
43
+ *
44
+ * This utility allows you to define custom interceptor conditions while ensuring that
45
+ * default values are applied to any missing fields. By using generics, you can enforce
46
+ * strong typing when creating the fields for the interceptor condition, enhancing type safety.
47
+ *
48
+ * @template T - A type that extends `AuthBearerCondition`.
49
+ * @param value - An object of type `T` (extending `AuthBearerCondition`) to be enhanced with default values.
50
+ * @returns A new object of type `T` with default values assigned to any undefined properties.
51
+ */
52
+ export declare const createInterceptorCondition: <T extends BearerTokenCondition>(value: T) => T;
53
+ /**
54
+ * Conditionally updates the Keycloak token based on the provided request and conditions.
55
+ *
56
+ * @param req - The `HttpRequest` object being processed.
57
+ * @param keycloak - The Keycloak instance managing authentication.
58
+ * @param condition - An `AuthBearerCondition` object with the `shouldUpdateToken` function.
59
+ * @returns A `Promise<boolean>` indicating whether the token was successfully updated.
60
+ */
61
+ export declare const conditionallyUpdateToken: (req: HttpRequest<unknown>, keycloak: Keycloak, { shouldUpdateToken }: BearerTokenCondition) => Promise<boolean>;
62
+ /**
63
+ * Adds the Authorization header to an HTTP request and forwards it to the next handler.
64
+ *
65
+ * @param req - The original `HttpRequest` object.
66
+ * @param next - The `HttpHandlerFn` function for forwarding the HTTP request.
67
+ * @param keycloak - The Keycloak instance providing the authentication token.
68
+ * @param condition - An `AuthBearerCondition` object specifying header configuration.
69
+ * @returns An `Observable<HttpEvent<unknown>>` representing the HTTP response.
70
+ */
71
+ export declare const addAuthorizationHeader: (req: HttpRequest<unknown>, next: HttpHandlerFn, keycloak: Keycloak, condition: BearerTokenCondition) => Observable<HttpEvent<unknown>>;
@@ -1,5 +1,10 @@
1
1
  import * as i0 from "@angular/core";
2
2
  import * as i1 from "@angular/common";
3
+ /**
4
+ * @deprecated NgModules are deprecated in Keycloak Angular and will be removed in future versions.
5
+ * Use the new `provideKeycloak` function to load Keycloak in an Angular application.
6
+ * More info: https://github.com/mauriciovigolo/keycloak-angular/docs/migration-guides/v19.md
7
+ */
3
8
  export declare class CoreModule {
4
9
  static ɵfac: i0.ɵɵFactoryDeclaration<CoreModule, never>;
5
10
  static ɵmod: i0.ɵɵNgModuleDeclaration<CoreModule, never, [typeof i1.CommonModule], never>;
@@ -0,0 +1,53 @@
1
+ import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
2
+ import { Observable } from 'rxjs';
3
+ import { KeycloakService } from '../services/keycloak.service';
4
+ import * as i0 from "@angular/core";
5
+ /**
6
+ * This interceptor includes the bearer by default in all HttpClient requests.
7
+ *
8
+ * If you need to exclude some URLs from adding the bearer, please, take a look
9
+ * at the {@link KeycloakOptions} bearerExcludedUrls property.
10
+ *
11
+ * @deprecated KeycloakBearerInterceptor is deprecated and will be removed in future versions.
12
+ * Use the new functional interceptor such as `includeBearerTokenInterceptor`.
13
+ * More info: https://github.com/mauriciovigolo/keycloak-angular/docs/migration-guides/v19.md
14
+ */
15
+ export declare class KeycloakBearerInterceptor implements HttpInterceptor {
16
+ private keycloak;
17
+ constructor(keycloak: KeycloakService);
18
+ /**
19
+ * Calls to update the keycloak token if the request should update the token.
20
+ *
21
+ * @param req http request from @angular http module.
22
+ * @returns
23
+ * A promise boolean for the token update or noop result.
24
+ */
25
+ private conditionallyUpdateToken;
26
+ /**
27
+ * @deprecated
28
+ * Checks if the url is excluded from having the Bearer Authorization
29
+ * header added.
30
+ *
31
+ * @param req http request from @angular http module.
32
+ * @param excludedUrlRegex contains the url pattern and the http methods,
33
+ * excluded from adding the bearer at the Http Request.
34
+ */
35
+ private isUrlExcluded;
36
+ /**
37
+ * Intercept implementation that checks if the request url matches the excludedUrls.
38
+ * If not, adds the Authorization header to the request if the user is logged in.
39
+ *
40
+ * @param req
41
+ * @param next
42
+ */
43
+ intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>>;
44
+ /**
45
+ * Adds the token of the current user to the Authorization header
46
+ *
47
+ * @param req
48
+ * @param next
49
+ */
50
+ private handleRequestWithTokenHeader;
51
+ static ɵfac: i0.ɵɵFactoryDeclaration<KeycloakBearerInterceptor, never>;
52
+ static ɵprov: i0.ɵɵInjectableDeclaration<KeycloakBearerInterceptor>;
53
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * @license
3
+ * Copyright Mauricio Gemelli Vigolo and contributors.
4
+ *
5
+ * Use of this source code is governed by a MIT-style license that can be
6
+ * found in the LICENSE file at https://github.com/mauriciovigolo/keycloak-angular/blob/main/LICENSE.md
7
+ */
8
+ /**
9
+ * Keycloak event types, as described at the keycloak-js documentation:
10
+ * https://www.keycloak.org/docs/latest/securing_apps/index.html#callback-events
11
+ *
12
+ * @deprecated Keycloak Event based on the KeycloakService is deprecated and
13
+ * will be removed in future versions.
14
+ * Use the new `KEYCLOAK_EVENT_SIGNAL` injection token to listen for the keycloak
15
+ * events.
16
+ * More info: https://github.com/mauriciovigolo/keycloak-angular/docs/migration-guides/v19.md
17
+ */
18
+ export declare enum KeycloakEventTypeLegacy {
19
+ /**
20
+ * Called if there was an error during authentication.
21
+ */
22
+ OnAuthError = 0,
23
+ /**
24
+ * Called if the user is logged out
25
+ * (will only be called if the session status iframe is enabled, or in Cordova mode).
26
+ */
27
+ OnAuthLogout = 1,
28
+ /**
29
+ * Called if there was an error while trying to refresh the token.
30
+ */
31
+ OnAuthRefreshError = 2,
32
+ /**
33
+ * Called when the token is refreshed.
34
+ */
35
+ OnAuthRefreshSuccess = 3,
36
+ /**
37
+ * Called when a user is successfully authenticated.
38
+ */
39
+ OnAuthSuccess = 4,
40
+ /**
41
+ * Called when the adapter is initialized.
42
+ */
43
+ OnReady = 5,
44
+ /**
45
+ * Called when the access token is expired. If a refresh token is available the token
46
+ * can be refreshed with updateToken, or in cases where it is not (that is, with implicit flow)
47
+ * you can redirect to login screen to obtain a new access token.
48
+ */
49
+ OnTokenExpired = 6,
50
+ /**
51
+ * Called when a AIA has been requested by the application.
52
+ */
53
+ OnActionUpdate = 7
54
+ }
55
+ /**
56
+ * Structure of an event triggered by Keycloak, contains it's type
57
+ * and arguments (if any).
58
+ *
59
+ * @deprecated Keycloak Event based on the KeycloakService is deprecated and
60
+ * will be removed in future versions.
61
+ * Use the new `KEYCLOAK_EVENT_SIGNAL` injection token to listen for the keycloak
62
+ * events.
63
+ * More info: https://github.com/mauriciovigolo/keycloak-angular/docs/migration-guides/v19.md
64
+ */
65
+ export interface KeycloakEventLegacy {
66
+ /**
67
+ * Event type as described at {@link KeycloakEventTypeLegacy}.
68
+ */
69
+ type: KeycloakEventTypeLegacy;
70
+ /**
71
+ * Arguments from the keycloak-js event function.
72
+ */
73
+ args?: unknown;
74
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * @license
3
+ * Copyright Mauricio Gemelli Vigolo and contributors.
4
+ *
5
+ * Use of this source code is governed by a MIT-style license that can be
6
+ * found in the LICENSE file at https://github.com/mauriciovigolo/keycloak-angular/blob/main/LICENSE.md
7
+ */
8
+ import { HttpRequest } from '@angular/common/http';
9
+ /**
10
+ * HTTP Methods
11
+ *
12
+ * @deprecated KeycloakBearerInterceptor is deprecated and will be removed in future versions.
13
+ * Use the new functional interceptor `includeBearerTokenInterceptor`.
14
+ * More info: https://github.com/mauriciovigolo/keycloak-angular/docs/migration-guides/v19.md
15
+ */
16
+ export type HttpMethodsLegacy = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'PATCH';
17
+ /**
18
+ * ExcludedUrl type may be used to specify the url and the HTTP method that
19
+ * should not be intercepted by the KeycloakBearerInterceptor.
20
+ *
21
+ * Example:
22
+ * const excludedUrl: ExcludedUrl[] = [
23
+ * {
24
+ * url: 'reports/public'
25
+ * httpMethods: ['GET']
26
+ * }
27
+ * ]
28
+ *
29
+ * In the example above for URL reports/public and HTTP Method GET the
30
+ * bearer will not be automatically added.
31
+ *
32
+ * If the url is informed but httpMethod is undefined, then the bearer
33
+ * will not be added for all HTTP Methods.
34
+ *
35
+ * @deprecated KeycloakBearerInterceptor is deprecated and will be removed in future versions.
36
+ * Use the new functional interceptor `includeBearerTokenInterceptor`.
37
+ * More info: https://github.com/mauriciovigolo/keycloak-angular/docs/migration-guides/v19.md
38
+ */
39
+ export interface ExcludedUrl {
40
+ url: string;
41
+ httpMethods?: HttpMethodsLegacy[];
42
+ }
43
+ /**
44
+ * Similar to ExcludedUrl, contains the HTTP methods and a regex to
45
+ * include the url patterns.
46
+ * This interface is used internally by the KeycloakService.
47
+ *
48
+ * @deprecated KeycloakBearerInterceptor is deprecated and will be removed in future versions.
49
+ * Use the new functional interceptor `includeBearerTokenInterceptor`.
50
+ * More info: https://github.com/mauriciovigolo/keycloak-angular/docs/migration-guides/v19.md
51
+ */
52
+ export interface ExcludedUrlRegex {
53
+ urlPattern: RegExp;
54
+ httpMethods?: HttpMethodsLegacy[];
55
+ }
56
+ /**
57
+ * keycloak-angular initialization options.
58
+ *
59
+ * @deprecated KeycloakService is deprecated and will be removed in future versions.
60
+ * Use the new `provideKeycloak` method to load Keycloak in an Angular application.
61
+ * More info: https://github.com/mauriciovigolo/keycloak-angular/docs/migration-guides/v19.md
62
+ */
63
+ export interface KeycloakOptions {
64
+ /**
65
+ * Configs to init the keycloak-js library. If undefined, will look for a keycloak.json file
66
+ * at root of the project.
67
+ * If not undefined, can be a string meaning the url to the keycloak.json file or an object
68
+ * of {@link Keycloak.KeycloakConfig}. Use this configuration if you want to specify the keycloak server,
69
+ * realm, clientId. This is usefull if you have different configurations for production, stage
70
+ * and development environments. Hint: Make use of Angular environment configuration.
71
+ */
72
+ config?: string | Keycloak.KeycloakConfig;
73
+ /**
74
+ * Options to initialize the Keycloak adapter, matches the options as provided by Keycloak itself.
75
+ */
76
+ initOptions?: Keycloak.KeycloakInitOptions;
77
+ /**
78
+ * By default all requests made by Angular HttpClient will be intercepted in order to
79
+ * add the bearer in the Authorization Http Header. However, if this is a not desired
80
+ * feature, the enableBearerInterceptor must be false.
81
+ *
82
+ * Briefly, if enableBearerInterceptor === false, the bearer will not be added
83
+ * to the authorization header.
84
+ *
85
+ * The default value is true.
86
+ */
87
+ enableBearerInterceptor?: boolean;
88
+ /**
89
+ * Forces the execution of loadUserProfile after the keycloak initialization considering that the
90
+ * user logged in.
91
+ * This option is recommended if is desirable to have the user details at the beginning,
92
+ * so after the login, the loadUserProfile function will be called and its value cached.
93
+ *
94
+ * The default value is true.
95
+ */
96
+ loadUserProfileAtStartUp?: boolean;
97
+ /**
98
+ * @deprecated
99
+ * String Array to exclude the urls that should not have the Authorization Header automatically
100
+ * added. This library makes use of Angular Http Interceptor, to automatically add the Bearer
101
+ * token to the request.
102
+ */
103
+ bearerExcludedUrls?: (string | ExcludedUrl)[];
104
+ /**
105
+ * This value will be used as the Authorization Http Header name. The default value is
106
+ * **Authorization**. If the backend expects requests to have a token in a different header, you
107
+ * should change this value, i.e: **JWT-Authorization**. This will result in a Http Header
108
+ * Authorization as "JWT-Authorization: bearer <token>".
109
+ */
110
+ authorizationHeaderName?: string;
111
+ /**
112
+ * This value will be included in the Authorization Http Header param. The default value is
113
+ * **Bearer**, which will result in a Http Header Authorization as "Authorization: Bearer <token>".
114
+ *
115
+ * If any other value is needed by the backend in the authorization header, you should change this
116
+ * value.
117
+ *
118
+ * Warning: this value must be in compliance with the keycloak server instance and the adapter.
119
+ */
120
+ bearerPrefix?: string;
121
+ /**
122
+ * This value will be used to determine whether or not the token needs to be updated. If the token
123
+ * will expire is fewer seconds than the updateMinValidity value, then it will be updated.
124
+ *
125
+ * The default value is 20.
126
+ */
127
+ updateMinValidity?: number;
128
+ /**
129
+ * A function that will tell the KeycloakBearerInterceptor whether to add the token to the request
130
+ * or to leave the request as it is. If the returned value is `true`, the request will have the token
131
+ * present on it. If it is `false`, the token will be left off the request.
132
+ *
133
+ * The default is a function that always returns `true`.
134
+ */
135
+ shouldAddToken?: (request: HttpRequest<unknown>) => boolean;
136
+ /**
137
+ * A function that will tell the KeycloakBearerInterceptor if the token should be considered for
138
+ * updating as a part of the request being made. If the returned value is `true`, the request will
139
+ * check the token's expiry time and if it is less than the number of seconds configured by
140
+ * updateMinValidity then it will be updated before the request is made. If the returned value is
141
+ * false, the token will not be updated.
142
+ *
143
+ * The default is a function that always returns `true`.
144
+ */
145
+ shouldUpdateToken?: (request: HttpRequest<unknown>) => boolean;
146
+ }