To integrate Keycloak into an Angular application using NgModule, you must initialize the KeycloakService during the application bootstrap process using an APP_INITIALIZER provider. This ensures Keycloak is ready before the app starts.
Note: This implementation is deprecated. It is recommended to migrate to the provideKeycloak function for modern Angular applications. However, for existing NgModule-based apps, follow this pattern:
- Import
KeycloakAngularModule in your AppModule. - Create an initialization factory function that calls
keycloak.init(). - Provide the factory using
APP_INITIALIZER with KeycloakService as a dependency.
To enable silent SSO (which avoids full page redirects by using a hidden iframe), you must also serve a static HTML file at the path specified in silentCheckSsoRedirectUri.
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',
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 {}