Easy Keycloak integration for Angular applications.
Installations
npm install keycloak-angular
Developer Guide
Typescript
No
Module System
ESM
Node Version
20.18.1
NPM Version
10.8.2
Score
76.1
Supply Chain
97.6
Quality
92.2
Maintenance
100
Vulnerability
85.6
License
Releases
Contributors
Languages
TypeScript (93.09%)
HTML (3.41%)
CSS (1.77%)
JavaScript (1.73%)
Developer
mauriciovigolo
Download Statistics
Total Downloads
12,928,834
Last Day
7,232
Last Week
72,504
Last Month
382,618
Last Year
4,195,689
GitHub Statistics
745 Stars
503 Commits
281 Forks
35 Watching
1 Branches
33 Contributors
Bundle Size
15.77 kB
Minified
4.37 kB
Minified + Gzipped
Package Meta Information
Latest Version
19.0.2
Package Id
keycloak-angular@19.0.2
Unpacked Size
246.92 kB
Size
55.74 kB
File Count
25
NPM Version
10.8.2
Node Version
20.18.1
Publised On
24 Dec 2024
Total Downloads
Cumulative downloads
Total Downloads
12,928,834
Last day
-59.7%
7,232
Compared to previous day
Last week
-19.7%
72,504
Compared to previous week
Last month
10.7%
382,618
Compared to previous month
Last year
27.2%
4,195,689
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
1
Peer Dependencies
4
Keycloak Angular
Easy Keycloak integration for Angular applications.
- About
- Installation
- Setup
- Example project
- Keycloak Angular Features
- Guards
- HttpClient Interceptors
- Directives
- Keycloak Events Signal
- Contributors
- License
About
Keycloak-Angular
is a library that makes it easier to use keycloak-js in Angular applications. It provides the following features:
- Easy Initialization: Use the
provideKeycloak
function to set up and initialize a Keycloak instance withprovideAppInitializer
. This simplifies the setup process. - Angular DI Support: The Keycloak client instance can be injected directly into Angular components, services, and other parts of your app. There’s no need to create a custom service to wrap the client.
- HTTP Interceptors: Add the Bearer token to the
Authorization
header with built-in interceptors. These are modular and easy to configure using injection tokens. You can also create your own interceptors with provided helper functions. - Keycloak Events as Signals: Access Keycloak events easily using Angular Signals, provided through the
KEYCLOAK_EVENT_SIGNAL
injection token. - Automatic Token Refresh: Use the
withAutoRefreshToken
feature to automatically refresh tokens when they expire, considering the user activity and a sessionTimeout. - Custom Route Guards: Use the
createAuthGuard
factory to build guards forCanActivate
andCanActivateChild
, helping you secure routes with custom logic. - Role-Based Rendering: The
*kaHasRoles
directive lets you show or hide parts of the DOM based on the user’s resource or realm roles.
Installation
Run the following command to install both Keycloak Angular and the official Keycloak client library:
1npm install keycloak-angular keycloak-js
Note that keycloak-js
is a peer dependency of keycloak-angular
. This allows greater flexibility of choosing the right version of the Keycloak client for your project.
Versions
Angular | keycloak-js | keycloak-angular | Support |
---|---|---|---|
19.x | 18 - 26 | 19.x.x | New Features / Bugs |
18.x | 18 - 26 | 16.x.x | Bugs |
17.x | 18 - 25 | 15.x.x | - |
16.x | 18 - 25 | 14.x.x | - |
15.x | 18 - 21 | 13.x.x | - |
- Only the latest version of Angular listed in the table above is actively supported. This is because the compilation of Angular libraries can be incompatible between major versions.
- Starting with Angular v19, Keycloak-Angular will adopt the same major version numbering as Angular, making it easier to identify the correct version to use.
Choosing the right keycloak-js version
The Keycloak client documentation recommends to use the same version of your Keycloak server installation.
Setup
To initialize Keycloak, add provideKeycloak
to the providers
array in the ApplicationConfig
object (e.g., in app.config.ts
). If initOptions
is included, keycloak-angular
will automatically use provideAppInitializer
to handle initialization, following the recommended approach for starting dependencies.
Use the example code below as a guide for your application.
1import { provideRouter } from '@angular/router'; 2import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core'; 3import { provideKeycloak } from 'keycloak-angular'; 4 5import { routes } from './app.routes'; 6 7export const appConfig: ApplicationConfig = { 8 providers: [ 9 provideKeycloak({ 10 config: { 11 url: 'keycloak-server-url', 12 realm: 'realm-id', 13 clientId: 'client-id' 14 }, 15 initOptions: { 16 onLoad: 'check-sso', 17 silentCheckSsoRedirectUri: window.location.origin + '/silent-check-sso.html' 18 } 19 }), 20 provideZoneChangeDetection({ eventCoalescing: true }), 21 provideRouter(routes) 22 ] 23};
Important:
- You do not need to call
provideAppInitializer
ifinitOptions
is provided. The library handles this automatically.- If you need to control when
keycloak.init
is called, do not pass theinitOptions
to theprovideKeycloak
function. In this case, you are responsible for callingkeycloak.init
manually.- For reference, Angular's
APP_INITIALIZER
is deprecated. The recommended approach is to useprovideAppInitializer
.
In the example, Keycloak is configured to use a silent check-sso
. With this feature enabled, your browser avoids a full redirect to the Keycloak server and back to your application. Instead, this action is performed in a hidden iframe, allowing your application resources to be loaded and parsed only once during initialization, rather than reloading after a redirect.
To enable communication through the iframe, you need to serve a static HTML file from your application at the location specified in silentCheckSsoRedirectUri
.
Create a file named silent-check-sso.html
in the public
or assets
directory of your application and paste in the content shown below.
1<html> 2 <body> 3 <script> 4 parent.postMessage(location.href, location.origin); 5 </script> 6 </body> 7</html>
If you want to know more about these options and various other capabilities of the Keycloak client is recommended to read the JavaScript Adapter documentation.
Note About NgModules: Since Keycloak-Angular v19, the KeycloakAngularModule, KeycloakService, KeycloakBearerInterceptor and KeycloakAuthGuard are deprecated. If your application relies on NgModules, the library still has support for it. See more information on how to configure a NgModule the application.
Additional Resources For more details, refer to the provideKeycloak documentation.
Example project
If you want to see a complete overview a pre-configured client together with a working Keycloak server make sure to check out the standalone example project in this repository.
Keycloak Angular Features
Keycloak Angular Features enhance the library's capabilities and make it more modular and composable. These features are executed during application initialization and have access to Angular's Dependency Injection (DI) context. While there is currently only one feature available, more features will be introduced over time to address new scenarios and expand functionality.
Usage
The example below adds the withAutoRefreshToken
feature to Keycloak Angular. Note that this feature depends on two services provided by Keycloak Angular, which are: AutoRefreshTokenService
and UserActivityService
.
1import { provideKeycloak, withAutoRefreshToken, AutoRefreshTokenService, UserActivityService } from 'keycloak-angular'; 2 3export const provideKeycloakAngular = () => 4 provideKeycloak({ 5 config: { 6 url: 'keycloak-server-url', 7 realm: 'realm-id', 8 clientId: 'client-id' 9 }, 10 initOptions: { 11 onLoad: 'check-sso', 12 silentCheckSsoRedirectUri: window.location.origin + '/silent-check-sso.html' 13 }, 14 features: [ 15 withAutoRefreshToken({ 16 onInactivityTimeout: 'logout', 17 sessionTimeout: 60000 18 }) 19 ], 20 providers: [AutoRefreshTokenService, UserActivityService] 21 }); 22 23export const appConfig: ApplicationConfig = { 24 providers: [provideKeycloakAngular(), provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes)] 25};
Guards
The createAuthGuard
function is a higher-order function that simplifies the creation of guards relying on Keycloak data. It can be used to create CanActivateFn
or CanActivateChildFn
guards to protect the routes in your application.
Usage:
1import { ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot, UrlTree } from '@angular/router'; 2import { inject } from '@angular/core'; 3import { AuthGuardData, createAuthGuard } from 'keycloak-angular'; 4 5const isAccessAllowed = async ( 6 route: ActivatedRouteSnapshot, 7 _: RouterStateSnapshot, 8 authData: AuthGuardData 9): Promise<boolean | UrlTree> => { 10 const { authenticated, grantedRoles } = authData; 11 12 const requiredRole = route.data['role']; 13 if (!requiredRole) { 14 return false; 15 } 16 17 const hasRequiredRole = (role: string): boolean => 18 Object.values(grantedRoles.resourceRoles).some((roles) => roles.includes(role)); 19 20 if (authenticated && hasRequiredRole(requiredRole)) { 21 return true; 22 } 23 24 const router = inject(Router); 25 return router.parseUrl('/forbidden'); 26}; 27 28export const canActivateAuthRole = createAuthGuard<CanActivateFn>(isAccessAllowed);
The canActivateAuthRole
can be used in the route configuration to protect specific routes.
1import { Routes } from '@angular/router'; 2 3import { HomeComponent } from './components/home/home.component'; 4import { BooksComponent } from './components/books/books.component'; 5import { canActivateAuthRole } from './guards/auth-role.guard'; 6 7export const routes: Routes = [ 8 { path: '', component: HomeComponent }, 9 { 10 path: 'books', 11 component: BooksComponent, 12 canActivate: [canActivateAuthRole], 13 data: { role: 'view-books' } 14 } 15];
HttpClient Interceptors
Keycloak Angular provides HttpClient
interceptors for managing the Bearer Token in the HTTP request header.
By default, the library does not add the Bearer token to requests. It is the application's responsibility to configure and use the appropriate interceptors.
Important: This behavior is a significant change from previous versions of the library. The new approach is more declarative, secure, extendable and configurable. There are no services directly interacting with interceptors anymore. All configurations are handled within the interceptor itself.
Usage:
1import { provideRouter } from '@angular/router'; 2import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core'; 3import { provideHttpClient, withInterceptors } from '@angular/common/http'; 4import { 5 provideKeycloak, 6 createInterceptorCondition, 7 IncludeBearerTokenCondition, 8 INCLUDE_BEARER_TOKEN_INTERCEPTOR_CONFIG 9} from 'keycloak-angular'; 10 11import { routes } from './app.routes'; 12 13const urlCondition = createInterceptorCondition<IncludeBearerTokenCondition>({ 14 urlPattern: /^(http:\/\/localhost:8181)(\/.*)?$/i, 15 bearerPrefix: 'Bearer' 16}); 17 18export const appConfig: ApplicationConfig = { 19 providers: [ 20 provideKeycloak({ 21 config: { 22 url: 'keycloak-server-url', 23 realm: 'realm-id', 24 clientId: 'client-id' 25 }, 26 initOptions: { 27 onLoad: 'check-sso', 28 silentCheckSsoRedirectUri: window.location.origin + '/silent-check-sso.html' 29 } 30 }), 31 { 32 provide: INCLUDE_BEARER_TOKEN_INTERCEPTOR_CONFIG, 33 useValue: [urlCondition] // <-- Note that multiple conditions might be added. 34 }, 35 provideZoneChangeDetection({ eventCoalescing: true }), 36 provideRouter(routes), 37 provideHttpClient(withInterceptors([includeBearerTokenInterceptor])) 38 ] 39};
Additional Resources For more details on the available interceptors and their configurations, refer to the Keycloak HttpClient Interceptors documentation.
Directives
The library offers the *kaHasRoles
structural directive to evaluate if the user has the required Realm or Resource Roles to render or not to render a DOM.
Usage
In the component, add the HasRolesDirective
in the imports list.
1@Component({
2 selector: 'app-menu',
3 imports: [RouterModule, HasRolesDirective],
4 templateUrl: './menu.component.html',
5 styleUrls: ['./menu.component.css']
6})
7export class MenuComponent {}
1<nav class="menu"> 2 <div class="developer-status"><strong>Keycloak Events:</strong> {{ keycloakStatus }}</div> 3 4 <div class="actions"> 5 <a routerLink="/" class="action-item">Home</a> 6 <a routerLink="/books" class="action-item" *kaHasRoles="['view-books']">My Books</a> 7 </div> 8</nav>
Note:
If no resource is specified in*kaHasRoles="['view-books']"
, the default resource used will be the Keycloak application client ID.
Keycloak Events Signal
Keycloak Angular provides a Signal that allows Angular applications to easily react to keycloak-js
authorization and session events.
This Signal is created during the library's initialization and is available without any additional configuration. It can be accessed by injecting the KEYCLOAK_EVENT_SIGNAL
injection token.
Usage
1@Component({ 2 selector: 'app-menu', 3 templateUrl: './menu.component.html', 4 styleUrls: ['./menu.component.css'] 5}) 6export class MenuComponent { 7 authenticated = false; 8 9 constructor(private readonly keycloak: Keycloak) { 10 const keycloakSignal = inject(KEYCLOAK_EVENT_SIGNAL); 11 12 effect(() => { 13 const keycloakEvent = keycloakSignal(); 14 15 if (keycloakEvent.type === KeycloakEventType.Ready) { 16 this.authenticated = typeEventArgs<ReadyArgs>(keycloakEvent.args); 17 } 18 19 if (keycloakEvent.type === KeycloakEventType.AuthLogout) { 20 this.authenticated = false; 21 } 22 }); 23 } 24}
Contributors
Mauricio Vigolo | Jon Koops |
---|
If you want to contribute to the project, please check out the contributing document.
License
keycloak-angular is licensed under the MIT license.
No vulnerabilities found.
Reason
1 commit(s) and 14 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE.md:0
- Info: FSF or OSI recognized license: MIT License: LICENSE.md:0
Reason
SAST tool detected but not run on all commits
Details
- Info: SAST configuration detected: CodeQL
- Warn: 9 commits out of 19 are checked with a SAST tool
Reason
Found 6/22 approved changesets -- score normalized to 2
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Info: jobLevel 'actions' permission set to 'read': .github/workflows/codeql.yml:21
- Info: jobLevel 'contents' permission set to 'read': .github/workflows/codeql.yml:22
- Warn: no topLevel permission defined: .github/workflows/codeql.yml:1
- Warn: no topLevel permission defined: .github/workflows/main.yml:1
- Info: no jobLevel write permissions found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql.yml:27: update your workflow using https://app.stepsecurity.io/secureworkflow/mauriciovigolo/keycloak-angular/codeql.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql.yml:32: update your workflow using https://app.stepsecurity.io/secureworkflow/mauriciovigolo/keycloak-angular/codeql.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql.yml:38: update your workflow using https://app.stepsecurity.io/secureworkflow/mauriciovigolo/keycloak-angular/codeql.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codeql.yml:41: update your workflow using https://app.stepsecurity.io/secureworkflow/mauriciovigolo/keycloak-angular/codeql.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/mauriciovigolo/keycloak-angular/main.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:21: update your workflow using https://app.stepsecurity.io/secureworkflow/mauriciovigolo/keycloak-angular/main.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:28: update your workflow using https://app.stepsecurity.io/secureworkflow/mauriciovigolo/keycloak-angular/main.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:38: update your workflow using https://app.stepsecurity.io/secureworkflow/mauriciovigolo/keycloak-angular/main.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:51: update your workflow using https://app.stepsecurity.io/secureworkflow/mauriciovigolo/keycloak-angular/main.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:57: update your workflow using https://app.stepsecurity.io/secureworkflow/mauriciovigolo/keycloak-angular/main.yml/main?enable=pin
- Info: 0 out of 10 GitHub-owned GitHubAction dependencies pinned
- Info: 1 out of 1 npmCommand dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
17 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-8hc4-vh64-cxmj
- Warn: Project is vulnerable to: GHSA-qwcr-r2fm-qrc7
- Warn: Project is vulnerable to: GHSA-pxg6-pf52-xh8x
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-qw6h-vgh9-j6wx
- Warn: Project is vulnerable to: GHSA-c7qv-q95q-8v27
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-mwcw-c2x4-8c55
- Warn: Project is vulnerable to: GHSA-9wv6-86v2-598j
- Warn: Project is vulnerable to: GHSA-rhx6-c78j-4q9w
- Warn: Project is vulnerable to: GHSA-gcx4-mw62-g8wm
- Warn: Project is vulnerable to: GHSA-m6fv-jmcg-4jfg
- Warn: Project is vulnerable to: GHSA-cm22-4g7w-348p
- Warn: Project is vulnerable to: GHSA-3g92-w8c5-73pq
- Warn: Project is vulnerable to: GHSA-4vvj-4cpr-p986 / GHSA-64vr-g452-qvp3
- Warn: Project is vulnerable to: GHSA-9cwx-2883-4wfx
- Warn: Project is vulnerable to: GHSA-3h5v-q93c-6h6q
Score
4.6
/10
Last Scanned on 2024-12-16
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to keycloak-angular
@keycloakify/angular
Angular Components for Keycloakify
keycloak-angular-ionic-capacitor
Easy Keycloak setup for Angular applications
@gabrielfox/keycloak-angular
Easy Keycloak setup for Angular applications
@sbb-esta/angular-keycloak
🛈 We recommend [angular-oauth2-oidc](https://www.npmjs.com/package/angular-oauth2-oidc) to be used for authentication. See the [documentation](https://manfredsteyer.github.io/angular-oauth2-oidc/docs/index.html) for details.