![require(esm) Backported to Node.js 20, Paving the Way for ESM-Only Packages](https://cdn.sanity.io/images/cgdhsj6q/production/be8ab80c8efa5907bc341c6fefe9aa20d239d890-1600x1097.png?w=400&fit=max&auto=format)
Security News
require(esm) Backported to Node.js 20, Paving the Way for ESM-Only Packages
require(esm) backported to Node.js 20, easing the transition to ESM-only packages and reducing complexity for developers as Node 18 nears end-of-life.
keycloak-angular
Advanced tools
The keycloak-angular package is an Angular library that provides integration with Keycloak, an open-source identity and access management solution. It allows Angular applications to easily authenticate users and manage user sessions using Keycloak.
User Authentication
This feature allows you to initialize Keycloak in your Angular application and enforce user authentication. The code sample demonstrates how to configure Keycloak with the server URL, realm, and client ID, and ensure that the user is logged in before accessing the application.
import { KeycloakService } from 'keycloak-angular';
constructor(private keycloakService: KeycloakService) {}
async ngOnInit() {
await this.keycloakService.init({
config: {
url: 'https://keycloak-server/auth',
realm: 'my-realm',
clientId: 'my-client'
},
initOptions: {
onLoad: 'login-required'
}
});
}
Role-Based Access Control
This feature enables role-based access control by checking if the authenticated user has a specific role. The code sample shows how to use the KeycloakService to verify if the user possesses a particular role, which can be used to control access to certain parts of the application.
import { KeycloakService } from 'keycloak-angular';
constructor(private keycloakService: KeycloakService) {}
hasRole(role: string): boolean {
return this.keycloakService.isUserInRole(role);
}
Token Management
This feature provides token management capabilities, allowing you to retrieve the current user's authentication token. The code sample demonstrates how to use the KeycloakService to obtain the token, which can be used for making authenticated API requests.
import { KeycloakService } from 'keycloak-angular';
constructor(private keycloakService: KeycloakService) {}
async getToken(): Promise<string> {
return await this.keycloakService.getToken();
}
The angular-oauth2-oidc package is another popular library for implementing OAuth2 and OpenID Connect (OIDC) authentication in Angular applications. It provides similar functionalities to keycloak-angular, such as user authentication and token management, but is more generic and can be used with any OAuth2/OIDC compliant identity provider, not just Keycloak.
The oidc-client package is a JavaScript library for managing OpenID Connect (OIDC) authentication. While it is not specific to Angular, it can be integrated into Angular applications to handle authentication flows. Compared to keycloak-angular, oidc-client offers more flexibility in terms of identity provider support but requires more manual setup and integration.
Easy Keycloak setup for Angular applications.
This library helps you to use keycloak-js in Angular applications providing the following features:
keycloak-js
methods to be used in Angular, giving extra
functionalities to the original functions and adding new methods to make it easier to be consumed by
Angular applications.Run the following command to install both Keycloak Angular and the official Keycloak client library:
npm install keycloak-angular keycloak-js
Note that keycloak-js
is a peer dependency of Keycloak Angular. This change allows greater flexibility of choosing the right version of the Keycloak client version for your project.
Angular | keycloak-angular | keycloak-js | Support |
---|---|---|---|
13.x | 9.x.x | 10 - 16 | Bugs / New Features |
11.x - 12.x | 8.4.0 | 10 - 15 | None |
Only the latest version of Angular in the table above is actively supported. This is due to the fact that compilation of Angular libraries is incompatible between major versions.
Note: In keycloak-angular v.9, it is needed to add allowSyntheticDefaultImports: true
in the tsconfig.json file in your project. There is an issue in the keycloak project to update the typescript definitions file and solve the problem.
The Keycloak client documentation recommends to use the same version of your Keycloak installation.
A best practice is to load the JavaScript adapter directly from Keycloak Server as it will automatically be updated when you upgrade the server. If you copy the adapter to your web application instead, make sure you upgrade the adapter only after you have upgraded the server.
In order to make sure Keycloak is initialized when your application is bootstrapped you will have to add an APP_INITIALIZER
provider to your AppModule
. This provider will call the initializeKeycloak
factory function shown below which will set up the Keycloak service so that it can be used in your application.
Use the code provided below as an example and implement it's functionality in your application. In this process ensure that the configuration you are providing matches that of your client as configured in Keycloak.
import { APP_INITIALIZER, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { KeycloakAngularModule, KeycloakService } from 'keycloak-angular';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
function initializeKeycloak(keycloak: KeycloakService) {
return () =>
keycloak.init({
config: {
url: 'http://localhost:8080/auth',
realm: 'your-realm',
clientId: 'your-client-id'
},
initOptions: {
onLoad: 'check-sso',
silentCheckSsoRedirectUri:
window.location.origin + '/assets/silent-check-sso.html'
}
});
}
@NgModule({
declarations: [AppComponent],
imports: [AppRoutingModule, BrowserModule, KeycloakAngularModule],
providers: [
{
provide: APP_INITIALIZER,
useFactory: initializeKeycloak,
multi: true,
deps: [KeycloakService]
}
],
bootstrap: [AppComponent]
})
export class AppModule {}
In the example we have set up Keycloak to use a silent check-sso
. With this feature enabled, your browser will not do a full redirect to the Keycloak server and back to your application, instead this action will be performed in a hidden iframe, so your application resources only need to be loaded and parsed once by the browser when the app is initialized and not again after the redirect back from Keycloak to your app.
To ensure that Keycloak can communicate through the iframe you will have to serve a static HTML asset from your application at the location provided in silentCheckSsoRedirectUri
.
Create a file called silent-check-sso.html
in the assets
directory of your application and paste in the contents as seen below.
<html>
<body>
<script>
parent.postMessage(location.href, location.origin);
</script>
</body>
</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.
If you want to see an complete overview a pre-configured client together with a working Keycloak server make sure to check out the example project in this repository.
A generic AuthGuard, KeycloakAuthGuard
is provided to help you protect authenticated routes in your application. This guard provides you with information to see if the user is logged in and a list of roles from that belong to the user. In your implementation you just need to implement the desired logic to protect your routes.
To write your own implementation extend the KeycloakAuthGuard
class and implement the isAccessAllowed
method. For example the code provided below checks if the user is authenticated and if not the user is requested to sign in. It also checks if the user has the correct roles which could be provided by passing the roles
field into the data of the route.
import { Injectable } from '@angular/core';
import {
ActivatedRouteSnapshot,
Router,
RouterStateSnapshot
} from '@angular/router';
import { KeycloakAuthGuard, KeycloakService } from 'keycloak-angular';
@Injectable({
providedIn: 'root'
})
export class AuthGuard extends KeycloakAuthGuard {
constructor(
protected readonly router: Router,
protected readonly keycloak: KeycloakService
) {
super(router, keycloak);
}
public async isAccessAllowed(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
) {
// Force the user to log in if currently unauthenticated.
if (!this.authenticated) {
await this.keycloak.login({
redirectUri: window.location.origin + state.url
});
}
// Get the roles required from the route.
const requiredRoles = route.data.roles;
// Allow the user to to proceed if no additional roles are required to access the route.
if (!(requiredRoles instanceof Array) || requiredRoles.length === 0) {
return true;
}
// Allow the user to proceed if all the required roles are present.
return requiredRoles.every((role) => this.roles.includes(role));
}
}
By default, all HttpClient requests will add the Authorization header in the format of: Authorization: Bearer **_TOKEN_**
.
There is also the possibility to exclude requests that should not have the authorization header. This is accomplished by implementing the shouldAddToken
method in the keycloak initialization. For example, the configuration below will not add the token to GET
requests that match the paths /assets
or /clients/public
:
await keycloak.init({
config: {
url: 'http://localhost:8080/auth',
realm: 'your-realm',
clientId: 'your-client-id'
},
shouldAddToken: (request) => {
const { method, url } = request;
const isGetRequest = 'GET' === method.toUpperCase();
const acceptablePaths = ['/assets', '/clients/public'];
const isAcceptablePathMatch = urls.some((path) => url.includes(path));
return !(isGetRequest && isAcceptablePathMatch);
}
});
In the case where your application frequently polls an authenticated endpoint, you will find that users will not be logged out automatically over time. If that functionality is not desirable, you can add an http header to the polling requests then configure the shouldUpdateToken
option in the keycloak initialization.
In the example below, any http requests with the header token-update: false
will not trigger the user's keycloak token to be updated.
await keycloak.init({
config: {
url: 'http://localhost:8080/auth',
realm: 'your-realm',
clientId: 'your-client-id'
},
bearerExcludedUrls: ['/assets', '/clients/public'],
shouldUpdateToken: (request) => {
return !request.headers.get('token-update') === 'false';
}
});
The callback events from keycloak-js are available through a RxJS subject which is defined by keycloakEvents$
.
For example you make keycloak-angular auto refreshing your access token when expired:
keycloakService.keycloakEvents$.subscribe({
next: (e) => {
if (e.type == KeycloakEventType.OnTokenExpired) {
keycloakService.updateToken(20);
}
}
});
Mauricio Gemelli Vigolo | Jon Koops | Frederik Prijck | Jonathan Share | jmparra | Marcel Német | Raphael Alex Silva Abreu |
---|
If you want to contribute to the project, please check out the contributing document.
keycloak-angular is licensed under the MIT license.
FAQs
Easy Keycloak integration for Angular applications.
The npm package keycloak-angular receives a total of 0 weekly downloads. As such, keycloak-angular popularity was classified as not popular.
We found that keycloak-angular demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
require(esm) backported to Node.js 20, easing the transition to ESM-only packages and reducing complexity for developers as Node 18 nears end-of-life.
Security News
PyPI now supports iOS and Android wheels, making it easier for Python developers to distribute mobile packages.
Security News
Create React App is officially deprecated due to React 19 issues and lack of maintenance—developers should switch to Vite or other modern alternatives.