Gathering detailed insights and metrics for keycloak-angular
Gathering detailed insights and metrics for keycloak-angular
Gathering detailed insights and metrics for keycloak-angular
Gathering detailed insights and metrics for 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.
Easy Keycloak integration for Angular applications.
npm install keycloak-angular
Typescript
Module System
Node Version
NPM Version
76.1
Supply Chain
97.6
Quality
92.2
Maintenance
100
Vulnerability
85.6
License
TypeScript (93.09%)
HTML (3.41%)
CSS (1.77%)
JavaScript (1.73%)
Total Downloads
12,928,834
Last Day
7,232
Last Week
72,504
Last Month
382,618
Last Year
4,195,689
745 Stars
503 Commits
281 Forks
35 Watching
1 Branches
33 Contributors
Minified
Minified + Gzipped
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
Cumulative downloads
Total Downloads
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
1
4
Easy Keycloak integration for Angular applications.
Keycloak-Angular
is a library that makes it easier to use keycloak-js in Angular applications. It provides the following features:
provideKeycloak
function to set up and initialize a Keycloak instance with provideAppInitializer
. This simplifies the setup process.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_EVENT_SIGNAL
injection token.withAutoRefreshToken
feature to automatically refresh tokens when they expire, considering the user activity and a sessionTimeout.createAuthGuard
factory to build guards for CanActivate
and CanActivateChild
, helping you secure routes with custom logic.*kaHasRoles
directive lets you show or hide parts of the DOM based on the user’s resource or realm roles.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.
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.
The Keycloak client documentation recommends to use the same version of your Keycloak server installation.
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.
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 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.
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};
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.
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];
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.
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.
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.
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 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.
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}
Mauricio Vigolo | Jon Koops |
---|
If you want to contribute to the project, please check out the contributing document.
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
Reason
SAST tool detected but not run on all commits
Details
Reason
Found 6/22 approved changesets -- score normalized to 2
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
17 existing vulnerabilities detected
Details
Score
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 More