Before you start integrating Keycloak with your Angular application, you need to know that Keycloak offer OpenID Connect (OIDC) Protocol support. If you want to integrate OpenID Connect with Angular, you can have a look at this OpenID Connect Angular Guide.
How to set up Keycloak in an Angular Project
Keycloak is an open-source identity and access management solution that is highly extensible and provides robust security for your applications. Integrating Keycloak into your Angular project can be done with the keycloak-angular
package. This guide will walk you through the process of setting up Keycloak in your Angular project using keycloak-angular.
Prerequisites
Before you begin, ensure you have the following:
- Node.js and npm installed on your development machine.
- Angular CLI installed.
- Access to a Keycloak server instance or you can set up one locally for testing purposes.
Installation
Install keycloak-angular and keycloak-js packages via npm:
npm install keycloak-angular keycloak-js
Configuration
Angular Setup
In your Angular project, you need to initialize Keycloak when your application starts. This ensures that Keycloak is ready for authentication throughout your application. Modify your AppModule to include the initialization logic:
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', // URL to your Keycloak instance
realm: 'your-realm', // Your Keycloak realm
clientId: 'your-client-id' // Client ID configured in Keycloak
},
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 {}
Create Silent Check-Sso HTML File:
Create a file named silent-check-sso.html inside the assets directory of your Angular project with the following content:
<html>
<body>
<script>
parent.postMessage(location.href, location.origin);
</script>
</body>
</html>
Usage
AuthGuard
keycloak-angular
provides a generic AuthGuard, KeycloakAuthGuard, to protect authenticated routes in your application. You can extend this guard and implement your own logic based on your application requirements.
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
) {
// Your authentication logic here
}
}
HttpClient Interceptor
keycloak-angular
provides an HttpClient interceptor to add the Authorization header to all HttpClient requests. You can configure exclusions and other options as needed.
Keycloak-js Events
Events from keycloak-js
can be accessed through the keycloakEvents$
RxJS subject provided by keycloak-angular. You can utilize these events for various functionalities, such as auto-refreshing access tokens.
For further details and advanced configurations, refer to the official Keycloak Angular Github and Keycloak Documentation.