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/README.md +39 -2
- package/fesm2022/keycloak-angular.mjs +101 -62
- package/fesm2022/keycloak-angular.mjs.map +1 -1
- package/index.d.ts +1534 -3
- package/package.json +5 -4
- package/lib/directives/has-roles.directive.d.ts +0 -95
- package/lib/features/keycloak.feature.d.ts +0 -43
- package/lib/features/with-refresh-token.feature.d.ts +0 -66
- package/lib/guards/auth.guard.d.ts +0 -75
- package/lib/interceptors/custom-bearer-token.interceptor.d.ts +0 -97
- package/lib/interceptors/include-bearer-token.interceptor.d.ts +0 -111
- package/lib/interceptors/keycloak.interceptor.d.ts +0 -71
- package/lib/legacy/core/core.module.d.ts +0 -12
- package/lib/legacy/core/interceptors/keycloak-bearer.interceptor.d.ts +0 -53
- package/lib/legacy/core/interfaces/keycloak-event.d.ts +0 -74
- package/lib/legacy/core/interfaces/keycloak-options.d.ts +0 -146
- package/lib/legacy/core/services/keycloak-auth-guard.d.ts +0 -50
- package/lib/legacy/core/services/keycloak.service.d.ts +0 -316
- package/lib/legacy/keycloak-angular.module.d.ts +0 -12
- package/lib/legacy/public_api.d.ts +0 -14
- package/lib/provide-keycloak.d.ts +0 -74
- package/lib/services/auto-refresh-token.service.d.ts +0 -47
- package/lib/services/user-activity.service.d.ts +0 -66
- package/lib/signals/keycloak-events-signal.d.ts +0 -118
- package/public_api.d.ts +0 -19
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "keycloak-angular",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "20.1.0",
|
|
4
4
|
"description": "Easy Keycloak integration for Angular applications.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -26,9 +26,10 @@
|
|
|
26
26
|
"oidc"
|
|
27
27
|
],
|
|
28
28
|
"peerDependencies": {
|
|
29
|
-
"@angular/common": "^
|
|
30
|
-
"@angular/core": "^
|
|
31
|
-
"@angular/router": "^
|
|
29
|
+
"@angular/common": "^20",
|
|
30
|
+
"@angular/core": "^20",
|
|
31
|
+
"@angular/router": "^20",
|
|
32
|
+
"rxjs": "^7",
|
|
32
33
|
"keycloak-js": "^18 || ^19 || ^20 || ^21 || ^22 || ^23 || ^24 || ^25 || ^26"
|
|
33
34
|
},
|
|
34
35
|
"dependencies": {
|
|
@@ -1,95 +0,0 @@
|
|
|
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 { TemplateRef, ViewContainerRef } from '@angular/core';
|
|
9
|
-
import Keycloak from 'keycloak-js';
|
|
10
|
-
import * as i0 from "@angular/core";
|
|
11
|
-
/**
|
|
12
|
-
* Structural directive to conditionally display elements based on Keycloak user roles.
|
|
13
|
-
*
|
|
14
|
-
* This directive checks if the authenticated user has at least one of the specified roles.
|
|
15
|
-
* Roles can be validated against a specific **resource (client ID)** or the **realm**.
|
|
16
|
-
*
|
|
17
|
-
* ### Features:
|
|
18
|
-
* - Supports role checking in both **resources (client-level roles)** and the **realm**.
|
|
19
|
-
* - Accepts an array of roles to match.
|
|
20
|
-
* - Optional configuration to check realm-level roles.
|
|
21
|
-
*
|
|
22
|
-
* ### Inputs:
|
|
23
|
-
* - `kaHasRoles` (Required): Array of roles to validate.
|
|
24
|
-
* - `resource` (Optional): The client ID or resource name to validate resource-level roles.
|
|
25
|
-
* - `checkRealm` (Optional): A boolean flag to enable realm role validation (default is `false`).
|
|
26
|
-
*
|
|
27
|
-
* ### Requirements:
|
|
28
|
-
* - A Keycloak instance must be injected via Angular's dependency injection.
|
|
29
|
-
* - The user must be authenticated in Keycloak.
|
|
30
|
-
*
|
|
31
|
-
* @example
|
|
32
|
-
* #### Example 1: Check for Global Realm Roles
|
|
33
|
-
* Show the content only if the user has the `admin` or `editor` role in the realm.
|
|
34
|
-
* ```html
|
|
35
|
-
* <div *kaHasRoles="['admin', 'editor']; checkRealm:true">
|
|
36
|
-
* <p>This content is visible only to users with 'admin' or 'editor' realm roles.</p>
|
|
37
|
-
* </div>
|
|
38
|
-
* ```
|
|
39
|
-
*
|
|
40
|
-
* @example
|
|
41
|
-
* #### Example 2: Check for Resource Roles
|
|
42
|
-
* Show the content only if the user has the `read` or `write` role for a specific resource (`my-client`).
|
|
43
|
-
* ```html
|
|
44
|
-
* <div *kaHasRoles="['read', 'write']; resource:'my-client'">
|
|
45
|
-
* <p>This content is visible only to users with 'read' or 'write' roles for 'my-client'.</p>
|
|
46
|
-
* </div>
|
|
47
|
-
* ```
|
|
48
|
-
*
|
|
49
|
-
* @example
|
|
50
|
-
* #### Example 3: Check for Both Resource and Realm Roles
|
|
51
|
-
* Show the content if the user has the roles in either the realm or a resource.
|
|
52
|
-
* ```html
|
|
53
|
-
* <div *kaHasRoles="['admin', 'write']; resource:'my-client' checkRealm:true">
|
|
54
|
-
* <p>This content is visible to users with 'admin' in the realm or 'write' in 'my-client'.</p>
|
|
55
|
-
* </div>
|
|
56
|
-
* ```
|
|
57
|
-
*
|
|
58
|
-
* @example
|
|
59
|
-
* #### Example 4: Fallback Content When Roles Do Not Match
|
|
60
|
-
* Use an `<ng-template>` to display fallback content if the user lacks the required roles.
|
|
61
|
-
* ```html
|
|
62
|
-
* <div *kaHasRoles="['admin']; resource:'my-client'">
|
|
63
|
-
* <p>Welcome, Admin!</p>
|
|
64
|
-
* </div>
|
|
65
|
-
* <ng-template #noAccess>
|
|
66
|
-
* <p>Access Denied</p>
|
|
67
|
-
* </ng-template>
|
|
68
|
-
* ```
|
|
69
|
-
*/
|
|
70
|
-
export declare class HasRolesDirective {
|
|
71
|
-
private templateRef;
|
|
72
|
-
private viewContainer;
|
|
73
|
-
private keycloak;
|
|
74
|
-
/**
|
|
75
|
-
* List of roles to validate against the resource or realm.
|
|
76
|
-
*/
|
|
77
|
-
roles: string[];
|
|
78
|
-
/**
|
|
79
|
-
* The resource (client ID) to validate roles against.
|
|
80
|
-
*/
|
|
81
|
-
resource?: string;
|
|
82
|
-
/**
|
|
83
|
-
* Flag to enable realm-level role validation.
|
|
84
|
-
*/
|
|
85
|
-
checkRealm: boolean;
|
|
86
|
-
constructor(templateRef: TemplateRef<unknown>, viewContainer: ViewContainerRef, keycloak: Keycloak);
|
|
87
|
-
private render;
|
|
88
|
-
/**
|
|
89
|
-
* Checks if the user has at least one of the specified roles in the resource or realm.
|
|
90
|
-
* @returns True if the user has access, false otherwise.
|
|
91
|
-
*/
|
|
92
|
-
private checkUserRoles;
|
|
93
|
-
static ɵfac: i0.ɵɵFactoryDeclaration<HasRolesDirective, never>;
|
|
94
|
-
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>;
|
|
95
|
-
}
|
|
@@ -1,43 +0,0 @@
|
|
|
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
|
-
/**
|
|
9
|
-
* Represents a feature from keycloak-angualr that can be configured during the library initialization.
|
|
10
|
-
*
|
|
11
|
-
* This type defines the structure of a feature that includes a `configure` method,
|
|
12
|
-
* which is responsible for setting up or initializing the feature's behavior or properties
|
|
13
|
-
* related to Keycloak.
|
|
14
|
-
*
|
|
15
|
-
* ### Usage:
|
|
16
|
-
* The `KeycloakFeature` type is typically used for defining modular, reusable Keycloak
|
|
17
|
-
* features that can be dynamically configured and integrated into an application.
|
|
18
|
-
*
|
|
19
|
-
* @property {() => void} configure - A method that initializes or configures the feature.
|
|
20
|
-
* This method is invoked to perform any setup or customization required for the feature.
|
|
21
|
-
*
|
|
22
|
-
* ### Example:
|
|
23
|
-
* ```typescript
|
|
24
|
-
* const withLoggingFeature: KeycloakFeature = {
|
|
25
|
-
* configure: () => {
|
|
26
|
-
* console.log('Configuring Keycloak logging feature');
|
|
27
|
-
* },
|
|
28
|
-
* };
|
|
29
|
-
*
|
|
30
|
-
* const withAnalyticsFeature: KeycloakFeature = {
|
|
31
|
-
* configure: () => {
|
|
32
|
-
* console.log('Configuring Keycloak analytics feature');
|
|
33
|
-
* },
|
|
34
|
-
* };
|
|
35
|
-
*
|
|
36
|
-
* // Configure and initialize features
|
|
37
|
-
* withLoggingFeature.configure();
|
|
38
|
-
* withAnalyticsFeature.configure();
|
|
39
|
-
* ```
|
|
40
|
-
*/
|
|
41
|
-
export type KeycloakFeature = {
|
|
42
|
-
configure: () => void;
|
|
43
|
-
};
|
|
@@ -1,66 +0,0 @@
|
|
|
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 { KeycloakFeature } from './keycloak.feature';
|
|
9
|
-
/**
|
|
10
|
-
* Options for configuring the auto-refresh token feature.
|
|
11
|
-
*
|
|
12
|
-
* This type defines the configuration parameters for enabling auto-refresh
|
|
13
|
-
* of Keycloak tokens and handling session inactivity scenarios.
|
|
14
|
-
*/
|
|
15
|
-
type WithRefreshTokenOptions = {
|
|
16
|
-
/**
|
|
17
|
-
* The session timeout duration in milliseconds. This specifies the time
|
|
18
|
-
* of inactivity after which the session is considered expired.
|
|
19
|
-
*
|
|
20
|
-
* Default value: `300000` milliseconds (5 minutes).
|
|
21
|
-
*/
|
|
22
|
-
sessionTimeout?: number;
|
|
23
|
-
/**
|
|
24
|
-
* Action to take when the session timeout due to inactivity occurs.
|
|
25
|
-
*
|
|
26
|
-
* - `'login'`: Execute the `keycloak.login` method.
|
|
27
|
-
* - `'logout'`: Logs the user out by calling the `keycloak.logout` method.
|
|
28
|
-
* - `'none'`: Takes no action on session timeout.
|
|
29
|
-
*
|
|
30
|
-
* Default value: `'logout'`.
|
|
31
|
-
*/
|
|
32
|
-
onInactivityTimeout?: 'login' | 'logout' | 'none';
|
|
33
|
-
};
|
|
34
|
-
/**
|
|
35
|
-
* Enables automatic token refresh and session inactivity handling for a
|
|
36
|
-
* Keycloak-enabled Angular application.
|
|
37
|
-
*
|
|
38
|
-
* This function initializes a service that tracks user interactions, such as
|
|
39
|
-
* mouse movements, touches, key presses, clicks, and scrolls. If user activity
|
|
40
|
-
* is detected, it periodically calls `Keycloak.updateToken` to ensure the bearer
|
|
41
|
-
* token remains valid and does not expire.
|
|
42
|
-
*
|
|
43
|
-
* If the session remains inactive beyond the defined `sessionTimeout`, the
|
|
44
|
-
* specified action (`logout`, `login`, or `none`) will be executed. By default,
|
|
45
|
-
* the service will call `keycloak.logout` upon inactivity timeout.
|
|
46
|
-
*
|
|
47
|
-
* Event tracking uses RxJS observables with a debounce of 300 milliseconds to
|
|
48
|
-
* monitor user interactions. When the Keycloak `OnTokenExpired` event occurs,
|
|
49
|
-
* the service checks the user's last activity timestamp. If the user has been
|
|
50
|
-
* active within the session timeout period, it refreshes the token using `updateToken`.
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
* @param options - Configuration options for the auto-refresh token feature.
|
|
54
|
-
* - `sessionTimeout` (optional): The duration in milliseconds after which
|
|
55
|
-
* the session is considered inactive. Defaults to `300000` (5 minutes).
|
|
56
|
-
* - `onInactivityTimeout` (optional): The action to take when session inactivity
|
|
57
|
-
* exceeds the specified timeout. Defaults to `'logout'`.
|
|
58
|
-
* - `'login'`: Execute `keycloak.login` function.
|
|
59
|
-
* - `'logout'`: Logs the user out by calling `keycloak.logout`.
|
|
60
|
-
* - `'none'`: No action is taken.
|
|
61
|
-
*
|
|
62
|
-
* @returns A `KeycloakFeature` instance that configures and enables the
|
|
63
|
-
* auto-refresh token functionality.
|
|
64
|
-
*/
|
|
65
|
-
export declare function withAutoRefreshToken(options?: WithRefreshTokenOptions): KeycloakFeature;
|
|
66
|
-
export {};
|
|
@@ -1,75 +0,0 @@
|
|
|
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 {};
|
|
@@ -1,97 +0,0 @@
|
|
|
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>>;
|
|
@@ -1,111 +0,0 @@
|
|
|
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>>;
|
|
@@ -1,71 +0,0 @@
|
|
|
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,12 +0,0 @@
|
|
|
1
|
-
import * as i0 from "@angular/core";
|
|
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
|
-
*/
|
|
8
|
-
export declare class CoreModule {
|
|
9
|
-
static ɵfac: i0.ɵɵFactoryDeclaration<CoreModule, never>;
|
|
10
|
-
static ɵmod: i0.ɵɵNgModuleDeclaration<CoreModule, never, [typeof i1.CommonModule], never>;
|
|
11
|
-
static ɵinj: i0.ɵɵInjectorDeclaration<CoreModule>;
|
|
12
|
-
}
|
|
@@ -1,53 +0,0 @@
|
|
|
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
|
-
}
|