### Install with pnpm Source: https://angular-auth-oidc-client.com/docs/intro Installs the angular-auth-oidc-client library using pnpm. ```bash pnpm add angular-auth-oidc-client ``` -------------------------------- ### Install with npm Source: https://angular-auth-oidc-client.com/docs/intro Installs the angular-auth-oidc-client library using npm. ```bash npm install angular-auth-oidc-client ``` -------------------------------- ### Install with Yarn Source: https://angular-auth-oidc-client.com/docs/intro Installs the angular-auth-oidc-client library using Yarn. ```bash yarn add angular-auth-oidc-client ``` -------------------------------- ### Install with ng add Source: https://angular-auth-oidc-client.com/docs/intro Installs the angular-auth-oidc-client library using Angular Schematics. ```bash ng add angular-auth-oidc-client ``` -------------------------------- ### Login and Logout Example Source: https://angular-auth-oidc-client.com/docs/intro Example of using OidcSecurityService for login and logout in an Angular component. ```typescript import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ /* ... */ }) export class AppComponent implements OnInit { private readonly oidcSecurityService = inject(OidcSecurityService); ngOnInit() { this.oidcSecurityService.checkAuth().subscribe(({ isAuthenticated, userData}) => /* ... */); } login() { this.oidcSecurityService.authorize(); } logout() { this.oidcSecurityService.logoff().subscribe((result) => console.log(result)); } } ``` -------------------------------- ### Custom Storage Service Implementation Source: https://angular-auth-oidc-client.com/docs/migrations/v13-to-v14 Example of implementing a custom storage service by extending AbstractSecurityStorage. ```typescript import { AbstractSecurityStorage } from 'angular-auth-oidc-client'; @Injectable() export class CustomStorage implements AbstractSecurityStorage { // ... } ``` -------------------------------- ### Recommended AutoLoginPartialRoutesGuard Usage Source: https://angular-auth-oidc-client.com/docs/migrations/v15-to-v16 Example showing the recommended usage of AutoLoginPartialRoutesGuard. ```typescript import { AutoLoginPartialRoutesGuard } from 'angular-auth-oidc-client'; const routes: Routes = [ { path: 'protected', component: ProtectedComponent, canActivate: [AutoLoginPartialRoutesGuard], // " }, ]; ``` -------------------------------- ### Content-Security-Policy Header Example Source: https://angular-auth-oidc-client.com/docs/documentation/deploy-to-different-domains Example of the Content-Security-Policy header configuration required for deploying to different domains, allowing iframes from the secure token service. ```http Content-Security-Policy: script-src 'self' 'unsafe-inline';style-src 'self' 'unsafe-inline';img-src 'self' data:;font-src 'self';frame-ancestors 'self' https://localhost:44318;block-all-mixed-content ``` -------------------------------- ### Route Guard Migration Source: https://angular-auth-oidc-client.com/docs/migrations/v15-to-v16 Example demonstrating the migration from the class-based `AutoLoginPartialRoutesGuard` to the functional guard `autoLoginPartialRoutesGuard` for route protection. ```typescript import { RouterModule, Routes } from '@angular/router'; import { AutoLoginPartialRoutesGuard } from 'angular-auth-oidc-client'; import { ProtectedComponent } from './protected/protected.component'; const appRoutes: Routes = [ { path: 'protected', component: ProtectedComponent, canActivate: [AutoLoginPartialRoutesGuard], }, { path: 'customers', loadChildren: () => import('./customers/customers.module').then((m) => m.CustomersModule), canLoad: [AutoLoginPartialRoutesGuard], }, ]; ``` ```typescript import { RouterModule, Routes } from '@angular/router'; import { AutoLoginPartialRoutesGuard } from 'angular-auth-oidc-client'; import { ProtectedComponent } from './protected/protected.component'; const appRoutes: Routes = [ { path: 'protected', component: ProtectedComponent, // 👇 using autoLoginPartialRoutesGuard canActivate: [autoLoginPartialRoutesGuard], }, { path: 'customers', loadChildren: () => import('./customers/customers.routes').then((m) => m.routes), // 👇 using autoLoginPartialRoutesGuard canMatch: [autoLoginPartialRoutesGuard], }, ]; ``` -------------------------------- ### userData$ Multiple Configs Example Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example JSON structure for `userData$` with multiple configurations. ```json { "userData": null, "allUserData": [ { "configId": "configId1", "userData": { "sub": "...", "preferred_username": "john@doe.org", "name": "john@doe.org", "email": "john@doe.org", "email_verified": false, "given_name": "john@doe.org", "role": "user", "amr": "pwd" } }, { "configId": "configId2", "userData": { "sub": "...", "preferred_username": "john@doe.org", "name": "john@doe.org", "email": "john@doe.org", "email_verified": false, "given_name": "john@doe.org", "role": "user", "amr": "pwd" } } ] } ``` -------------------------------- ### Static configuration - Old Source: https://angular-auth-oidc-client.com/docs/migrations/v11-to-v12 Example of static configuration in version 11. ```typescript import { APP_INITIALIZER, NgModule } from '@angular/core'; import { AuthModule, OidcConfigService } from 'angular-auth-oidc-client'; // ... export function configureAuth(oidcConfigService: OidcConfigService) { return () => oidcConfigService.withConfig({ /* your config here */ }); } @NgModule({ // ... imports: [ // ... AuthModule.forRoot(), ], providers: [ OidcConfigService, { provide: APP_INITIALIZER, useFactory: configureAuth, deps: [OidcConfigService], multi: true, }, ], // ... }) export class AppModule {} ``` -------------------------------- ### isAuthenticated$ Multiple Configs Example Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example JSON structure for `isAuthenticated$` with multiple configurations. ```json { "isAuthenticated": false, "allConfigsAuthenticated": [ { "configId": "configId1", "isAuthenticated": true }, { "configId": "configId2", "isAuthenticated": false } ] } ``` -------------------------------- ### getConfiguration() - Single or First Config Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of getting a single configuration, or the first one if multiple are configured. ```typescript // one config or the first one in case of multiple or null this.oidcSecurityService.getConfiguration().subscribe((config)=> ... ); ``` -------------------------------- ### NgModule Configuration Source: https://angular-auth-oidc-client.com/docs/intro Configures the library using AuthModule.forRoot in an Angular NgModule. ```typescript import { NgModule } from '@angular/core'; import { AuthModule, LogLevel } from 'angular-auth-oidc-client'; // ... @NgModule({ // ... imports: [ // ... AuthModule.forRoot({ config: { authority: '', redirectUrl: window.location.origin, postLogoutRedirectUri: window.location.origin, clientId: '', scope: 'openid profile email offline_access', responseType: 'code', silentRenew: true, useRefreshToken: true, logLevel: LogLevel.Debug, }, }), ], // ... }) export class AppModule {} ``` -------------------------------- ### userData Signal Example Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of how to use the `userData` signal. ```typescript userData = this.oidcSecurityService.userData; console.log(this.userData().userData); console.log(this.userData().userData?.name); console.log(this.userData().allUserData); ``` -------------------------------- ### userData$ Single Config Example Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example JSON structure for `userData$` with a single configuration. ```json { "userData": { "sub": "...", "preferred_username": "john@doe.org", "name": "john@doe.org", "email": "john@doe.org", "email_verified": false, "given_name": "john@doe.org", "role": "user", "amr": "pwd" }, "allUserData": [ { "configId": "configId", "userData": { "sub": "...", "preferred_username": "john@doe.org", "name": "john@doe.org", "email": "john@doe.org", "email_verified": false, "given_name": "john@doe.org", "role": "user", "amr": "pwd" } } ] } ``` -------------------------------- ### isAuthenticated$ Single Config Example Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example JSON structure for `isAuthenticated$` with a single configuration. ```json { "isAuthenticated": true, "allConfigsAuthenticated": [{ "configId": "configId1", "isAuthenticated": true }] } ``` -------------------------------- ### getConfigurations() Usage Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of retrieving all configured OpenID Connect configurations. ```typescript const allConfigs = this.oidcSecurityService.getConfigurations(); ``` -------------------------------- ### userData$ Example Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of how to subscribe to the `userData$` observable. ```typescript this.userData$ = this.oidcSecurityService.userData$; ``` -------------------------------- ### Standalone Configuration Source: https://angular-auth-oidc-client.com/docs/intro Configures the library using the provideAuth function in an Angular ApplicationConfig. ```typescript import { ApplicationConfig } from '@angular/core'; import { provideAuth, LogLevel } from 'angular-auth-oidc-client'; // ... export const appConfig: ApplicationConfig = { providers: [ provideAuth({ config: { authority: '', redirectUrl: window.location.origin, postLogoutRedirectUri: window.location.origin, clientId: '', scope: 'openid profile email offline_access', responseType: 'code', silentRenew: true, useRefreshToken: true, logLevel: LogLevel.Debug, }, }), // ... ], }; ``` -------------------------------- ### Standalone API Configuration (New) Source: https://angular-auth-oidc-client.com/docs/migrations/v15-to-v16 Configuration using provideAuth() for standalone applications. ```typescript import { ApplicationConfig } from '@angular/core'; import { bootstrapApplication } from '@angular/platform-browser'; import { provideAuth } from 'angular-auth-oidc-client'; import { AppComponent } from './app/app.component'; export const appConfig: ApplicationConfig = { providers: [ // provideAuth({ config: { /* Your config here */ }, }), ], }; bootstrapApplication(AppComponent, appConfig); ``` -------------------------------- ### Example Usage of Authenticated and UserData Signals Source: https://angular-auth-oidc-client.com/docs/migrations/v17-to-v18 This example demonstrates how to use the new `authenticated` and `userData` signals from the `OidcSecurityService` in an Angular component to conditionally display user information. ```typescript @Component({ selector: 'app-root', template: ` @if (authenticated().isAuthenticated) {
{{ userData() | json }}
} @else {
You are not authenticated.
} `, }) export class AppComponent { private readonly oidcSecurityService = inject(OidcSecurityService); // Signal containing authenticated state protected readonly authenticated = this.oidcSecurityService.authenticated; // Signal containing user data protected readonly userData = this.oidcSecurityService.userData; } ``` -------------------------------- ### getConfiguration() - Specific Config ID Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of getting a specific configuration by its ID. ```typescript // one config or null this.oidcSecurityService.getConfiguration('configId').subscribe((config)=> ... ); ``` -------------------------------- ### authenticated Signal Example Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of how to use the `authenticated` signal. ```typescript authenticated = this.oidcSecurityService.authenticated; console.log(authenticated().isAuthenticated); console.log(authenticated().allConfigsAuthenticated); ``` -------------------------------- ### Nginx Configuration for Content-Security-Policy Source: https://angular-auth-oidc-client.com/docs/documentation/deploy-to-different-domains Example of how to add the Content-Security-Policy header in an Nginx server configuration. ```nginx http { server { ... add_header Content-Security-Policy "script-src 'self' 'unsafe-inline';style-src 'self' 'unsafe-inline';img-src 'self' data:;font-src 'self';frame-ancestors 'self' https://localhost:44318;block-all-mixed-content"; ``` -------------------------------- ### Auto Login when the default route is not guarded Source: https://angular-auth-oidc-client.com/docs/documentation/auto-login This example demonstrates how to set up routes where some are freely accessible and others require a login that starts upon entering a protected route. It uses `autoLoginPartialRoutesGuard` for route protection. ```typescript import { autoLoginPartialRoutesGuard } from 'angular-auth-oidc-client'; const routes: Routes = [ { path: '', pathMatch: 'full', redirectTo: 'home' }, { path: 'home', component: HomeComponent }, { path: 'protected', component: ProtectedComponent, canActivate: [autoLoginPartialRoutesGuard], }, { path: 'customers', loadChildren: () => import('./customers/customers.routes').then((m) => m.customerRoutes), canLoad: [autoLoginPartialRoutesGuard], }, { path: 'unauthorized', component: UnauthorizedComponent }, ]; ``` -------------------------------- ### Deprecated AutoLoginAllRoutesGuard Usage Source: https://angular-auth-oidc-client.com/docs/migrations/v15-to-v16 Example showing the deprecated usage of AutoLoginAllRoutesGuard. ```typescript import { AutoLoginAllRoutesGuard } from 'angular-auth-oidc-client'; const routes: Routes = [ { path: 'protected', component: ProtectedComponent, canActivate: [AutoLoginAllRoutesGuard], // " }, ]; ``` -------------------------------- ### checkAuthMultiple Usage Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of how to use the checkAuthMultiple method to get authentication responses for all configs. ```typescript this.oidcSecurityService.checkAuthMultiple().subscribe((responses: LoginResponse[]) => { // ...use data }); ``` -------------------------------- ### isAuthenticated$ Example Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of how to access the `isAuthenticated$` observable. ```typescript this.isAuthenticated$ = this.oidcSecurityService.isAuthenticated$; ``` -------------------------------- ### Example of Setting Custom Parameters in ApplicationConfig Source: https://angular-auth-oidc-client.com/docs/documentation/custom-parameters Demonstrates how to set custom parameters like 'response_mode' and 'prompt' within the ApplicationConfig. ```typescript export const appConfig: ApplicationConfig = { providers: [ provideAuth({ authority: '', customParamsAuthRequest: { response_mode: 'fragment', prompt: 'consent', }, }), ], }; ``` -------------------------------- ### Loading config from endpoint (http) - Old Source: https://angular-auth-oidc-client.com/docs/migrations/v11-to-v12 Example of loading configuration from an HTTP endpoint in version 11. ```typescript import { HttpClient } from '@angular/common/http'; import { APP_INITIALIZER, NgModule } from '@angular/core'; import { AuthModule, OidcConfigService, OidcSecurityService, } from 'angular-auth-oidc-client'; import { map, switchMap } from 'rxjs/operators'; export function configureAuth( oidcConfigService: OidcConfigService, httpClient: HttpClient ) { const setupAction$ = httpClient.get(`https://...`).pipe( map((customConfig) => { return { /* your config mapping here */ }; }), switchMap((config) => oidcConfigService.withConfig(config)) ); return () => setupAction$.toPromise(); } @NgModule({ imports: [AuthModule.forRoot()], providers: [ OidcSecurityService, OidcConfigService, { provide: APP_INITIALIZER, useFactory: configureAuth, deps: [OidcConfigService, HttpClient], multi: true, }, ], exports: [AuthModule], }) export class AuthConfigModule {} ``` -------------------------------- ### Static configuration - New Source: https://angular-auth-oidc-client.com/docs/migrations/v11-to-v12 Example of static configuration in version 12, with the config object passed directly to AuthModule.forRoot. ```typescript import { NgModule } from '@angular/core'; import { AuthModule } from 'angular-auth-oidc-client'; // ... @NgModule({ // ... imports: [ // ... AuthModule.forRoot({ config: { /* your config here */ }, }), ], // ... }) export class AppModule {} ``` -------------------------------- ### Loading config from endpoint (http) - New Source: https://angular-auth-oidc-client.com/docs/migrations/v11-to-v12 Example of loading configuration from an HTTP endpoint in version 12, using StsConfigHttpLoader. ```typescript import { HttpClient } from '@angular/common/http'; import { NgModule } from '@angular/core'; import { AuthModule, StsConfigHttpLoader, StsConfigLoader, } from 'angular-auth-oidc-client'; import { map } from 'rxjs/operators'; export const httpLoaderFactory = (httpClient: HttpClient) => { const config$ = httpClient .get(`https://...`) .pipe( map((customConfig: any) => { return { /* your config mapping here */ }; }) ) .toPromise(); return new StsConfigHttpLoader(config$); }; @NgModule({ imports: [ AuthModule.forRoot({ loader: { provide: StsConfigLoader, useFactory: httpLoaderFactory, deps: [HttpClient], }, }), ], exports: [AuthModule], }) export class AuthConfigModule {} ``` -------------------------------- ### Class-based Route Guard Example Source: https://angular-auth-oidc-client.com/docs/documentation/guards An example of a class-based route guard that implements the CanActivate interface to check authentication status. ```typescript import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router'; import { OidcSecurityService } from 'angular-auth-oidc-client'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class AuthorizationGuard implements CanActivate { private readonly oidcSecurityService = inject(OidcSecurityService); private readonly router = inject(Router); canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable { return this.oidcSecurityService.isAuthenticated$.pipe( take(1), map(({ isAuthenticated }) => { // allow navigation if authenticated if (isAuthenticated) { return true; } // redirect if not authenticated return this.router.parseUrl('/unauthorized'); }) ); } } ``` ```typescript const appRoutes: Routes = [ { path: 'protected', component: , canActivate: [AuthorizationGuard] }, ]; ``` -------------------------------- ### Configure with NgModule Source: https://angular-auth-oidc-client.com/docs/documentation/configuration Example of configuring the auth module using `AuthModule.forRoot()` within an NgModule. ```typescript import { NgModule } from '@angular/core'; import { AuthModule } from 'angular-auth-oidc-client'; @NgModule({ imports: [ AuthModule.forRoot({ config: { /* Your config here */ }, }), ], exports: [AuthModule], }) export class AuthConfigModule {} ``` -------------------------------- ### Angular Module Configuration (Old) Source: https://angular-auth-oidc-client.com/docs/migrations/v15-to-v16 Configuration using AuthModule.forRoot() in an Angular Module. ```typescript import { NgModule } from '@angular/core'; import { AuthModule } from 'angular-auth-oidc-client'; @NgModule({ imports: [ AuthModule.forRoot({ config: { /* Your config here */ }, }), ], exports: [AuthModule], }) export class AuthConfigModule {} ``` -------------------------------- ### Getting static config from a service (sync) Source: https://angular-auth-oidc-client.com/docs/documentation/configuration You can also get the static config from a service. In this case you can use the `StsConfigStaticLoader` passing the config in the constructor. ```typescript @Injectable({ providedIn: 'root' }) export class ConfigService { getConfig(): OpenIdConfiguration { return { /* Your config here */ }; } } const authFactory = (configService: ConfigService) => { const config = configService.getConfig(); return new StsConfigStaticLoader(config); }; export const appConfig: ApplicationConfig = { providers: [ provideAuth({ loader: { provide: StsConfigLoader, useFactory: authFactory, deps: [ConfigService], }, }), ], }; ``` -------------------------------- ### Logout with POST method Source: https://angular-auth-oidc-client.com/docs/documentation/login-logout Example of how to perform a logout using the POST method by setting `logoffMethod` to 'POST' in `LogoutAuthOptions`. ```typescript logout() { // logoffMethod` - Which can be `GET` or `POST const logoutAuthOptions: LogoutAuthOptions = { customParams: { logout_hint: 'some-logout-hint', }, logoffMethod: 'POST', }; this.oidcSecurityService.logoff('', logoutAuthOptions) .subscribe((result) => console.log(result)); } ``` -------------------------------- ### App Initializer Auth Check Source: https://angular-auth-oidc-client.com/docs/documentation/configuration Example of using `withAppInitializerAuthCheck` to handle OAuth callbacks during app initialization. ```typescript import { ApplicationConfig } from '@angular/core'; import { provideAuth, withAppInitializerAuthCheck } from 'angular-auth-oidc-client'; export const appConfig: ApplicationConfig = { providers: [ provideAuth( { config: { /* Your config here */ }, }, withAppInitializerAuthCheck() ), ], }; ``` -------------------------------- ### Old AutoLoginGuard usage (securing the whole app) Source: https://angular-auth-oidc-client.com/docs/migrations/v11-to-v12 Example of how AutoLoginGuard was used to secure all routes in previous versions. ```typescript import { AutoLoginGuard } from 'angular-auth-oidc-client'; const appRoutes: Routes = [ { path: '', pathMatch: 'full', redirectTo: 'home' }, { path: 'home', component: HomeComponent, canActivate: [AutoLoginGuard] }, { path: 'protected', component: ProtectedComponent, canActivate: [AutoLoginGuard], }, { path: 'forbidden', component: ForbiddenComponent, canActivate: [AutoLoginGuard], }, { path: 'customers', loadChildren: () => import('./customers/customers.module').then((m) => m.CustomersModule), canLoad: [AutoLoginGuard], }, { path: 'unauthorized', component: UnauthorizedComponent }, ]; ``` -------------------------------- ### HTTP Interceptor Configuration (New) Source: https://angular-auth-oidc-client.com/docs/migrations/v15-to-v16 Configuring authInterceptor using provideHttpClient for standalone applications. ```typescript import { ApplicationConfig } from '@angular/core'; import { bootstrapApplication } from '@angular/platform-browser'; import { provideHttpClient, withInterceptors } from '@angular/common/http'; import { provideAuth, authInterceptor } from 'angular-auth-oidc-client'; import { AppComponent } from './app/app.component'; export const appConfig: ApplicationConfig = { providers: [ // provideHttpClient(withInterceptors([authInterceptor()])), provideAuth({ config: { /* Your config here */ }, }), ], }; bootstrapApplication(AppComponent, appConfig); ``` -------------------------------- ### Logoff and revoke tokens Source: https://angular-auth-oidc-client.com/docs/documentation/login-logout Example of how to use the `logoffAndRevokeTokens` method to revoke tokens and then log off. ```typescript logoffAndRevokeTokens() { this.oidcSecurityService.logoffAndRevokeTokens() .subscribe((result) => console.log(result)); } ``` -------------------------------- ### Functional Route Guard Example Source: https://angular-auth-oidc-client.com/docs/documentation/guards An example of a functional route guard that checks authentication status and redirects if not authenticated. ```typescript import { inject } from '@angular/core'; import { Router } from '@angular/router'; import { OidcSecurityService } from 'angular-auth-oidc-client'; import { map, take } from 'rxjs'; export const isAuthenticated = () => { const oidcSecurityService = inject(OidcSecurityService); const router = inject(Router); return oidcSecurityService.isAuthenticated$.pipe( take(1), map(({ isAuthenticated }) => { // allow navigation if authenticated if (isAuthenticated) { return true; } // redirect if not authenticated return router.parseUrl('/unauthorized'); }) ); }; ``` ```typescript const appRoutes: Routes = [ { path: 'protected', component: , canActivate: [isAuthenticated] }, ]; ``` -------------------------------- ### getAccessToken (first config) Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of retrieving the access token for the first or only configuration. ```typescript this.oidcSecurityService.getAccessToken().subscribe(/*...*/); ``` -------------------------------- ### authorizeWithPopUp Example 1 Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Basic usage of the authorizeWithPopUp method to initiate login via a popup. ```typescript this.oidcSecurityService.authorizeWithPopUp().subscribe(({ isAuthenticated, userData, accessToken, idToken, configId }) => { // ...use data }); ``` -------------------------------- ### Get Access Token for a specific config Source: https://angular-auth-oidc-client.com/docs/documentation/using-access-tokens Get the access token for a specific configuration ID. ```typescript this.oidcSecurityService.getAccessToken('configId').subscribe(at => ...); ``` -------------------------------- ### New AutoLoginAllRoutesGuard usage (securing the whole app) Source: https://angular-auth-oidc-client.com/docs/migrations/v11-to-v12 Example demonstrating the use of AutoLoginAllRoutesGuard for securing all routes in version 12. ```typescript import { AutoLoginAllRoutesGuard } from 'angular-auth-oidc-client'; const appRoutes: Routes = [ { path: '', pathMatch: 'full', redirectTo: 'home' }, { path: 'home', component: HomeComponent, canActivate: [AutoLoginAllRoutesGuard], }, { path: 'protected', component: ProtectedComponent, canActivate: [AutoLoginAllRoutesGuard], }, { path: 'forbidden', component: ForbiddenComponent, canActivate: [AutoLoginAllRoutesGuard], }, { path: 'customers', loadChildren: () => import('./customers/customers.module').then((m) => m.CustomersModule), canLoad: [AutoLoginAllRoutesGuard], }, { path: 'unauthorized', component: UnauthorizedComponent }, ]; ``` -------------------------------- ### Logout with custom parameters Source: https://angular-auth-oidc-client.com/docs/documentation/login-logout Example of how to use the `logoff` method with `LogoutAuthOptions` to pass custom parameters like `logout_hint`. ```typescript logout() { const logoutAuthOptions: LogoutAuthOptions = { customParams: { logout_hint: 'some-logout-hint', /* other params */ } }; // Use an empty string for the configId if this is not a multiple client // subscribe to the result if you expect the function to return. // => .subscribe((result) => console.log(result)); this.oidcSecurityService.logoff('configId', logoutAuthOptions); } ``` -------------------------------- ### checkAuth() - Basic Usage Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of initiating the authentication flow and subscribing to the result. ```typescript this.oidcSecurityService.checkAuth().subscribe(({ isAuthenticated, userData, accessToken, idToken, configId }) => { // ...use data }); ``` -------------------------------- ### getConfiguration Change Source: https://angular-auth-oidc-client.com/docs/migrations/v13-to-v14 Demonstrates the change in how getConfiguration is called, from a direct call to subscribing to an Observable. ```typescript const singleConfig = this.oidcSecurityService.getConfiguration(); ``` ```typescript this.oidcSecurityService.getConfiguration().subscribe((config)=> ... ); ``` -------------------------------- ### Custom Logger Service Implementation Source: https://angular-auth-oidc-client.com/docs/documentation/custom-logger Example of how to implement a custom logger service by extending AbstractLoggerService. ```typescript import { AbstractLoggerService } from 'angular-auth-oidc-client'; @Injectable() export class MyLoggerService implements AbstractLoggerService { // ... } ``` -------------------------------- ### getIdToken (first config) Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of retrieving the ID token for the first or only configuration. ```typescript this.oidcSecurityService.getIdToken().subscribe(/*...*/); ``` -------------------------------- ### Old AutoLoginGuard usage (securing parts of the app) Source: https://angular-auth-oidc-client.com/docs/migrations/v11-to-v12 Example of using AutoLoginGuard to secure only specific routes in previous versions. ```typescript import { AutoLoginGuard } from 'angular-auth-oidc-client'; const appRoutes: Routes = [ { path: '', pathMatch: 'full', redirectTo: 'home' }, { path: 'home', component: HomeComponent }, { path: 'protected', component: ProtectedComponent, canActivate: [AutoLoginGuard], }, { path: 'forbidden', component: ForbiddenComponent, canActivate: [AutoLoginGuard], }, { path: 'customers', loadChildren: () => import('./customers/customers.module').then((m) => m.CustomersModule), canLoad: [AutoLoginGuard], }, { path: 'unauthorized', component: UnauthorizedComponent }, ]; ``` -------------------------------- ### getAccessToken (specific config) Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of retrieving the access token for a specific configuration. ```typescript this.oidcSecurityService.getAccessToken('configId').subscribe(/*...*/); ``` -------------------------------- ### Logoff and revoke tokens with custom parameters Source: https://angular-auth-oidc-client.com/docs/documentation/login-logout Example of using `logoffAndRevokeTokens` with `LogoutAuthOptions` to include custom parameters. ```typescript logoffAndRevokeTokens() { const logoutAuthOptions: LogoutAuthOptions = { customParams: { logout_hint: 'some-logout-hint', }, }; this.oidcSecurityService.logoffAndRevokeTokens('', logoutAuthOptions) .subscribe((result) => console.log(result)); } ``` -------------------------------- ### Using multiple configs Source: https://angular-auth-oidc-client.com/docs/documentation/configuration You can pass an array of configs into the `provideAuth()` method. Each config will get an `configId` automatically if you do not set it for yourself. ```typescript import { ApplicationConfig } from '@angular/core'; import { provideAuth } from 'angular-auth-oidc-client'; export const appConfig: ApplicationConfig = { providers: [ provideAuth({ config: [ { // config1... }, { // config2... }, { // config3... }, //... ], }), ], }; ``` -------------------------------- ### forceRefreshSession Example 2 Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Usage of forceRefreshSession with custom parameters and a specific configuration ID. ```typescript const customParams: { some: 'params', } this.oidcSecurityService .forceRefreshSession(customParams, 'configId') .subscribe(({ isAuthenticated, userData, accessToken, idToken, configId }) => { }); ``` -------------------------------- ### logoff Example 1 Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Basic usage of the logoff method for local and server-side logout. ```typescript this.oidcSecurityService.logoff().subscribe((result) => console.log(result)); ``` -------------------------------- ### preloadAuthWellKnownDocument() - Multiple Configs Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of explicitly loading well-known endpoints for a specific configuration ID. ```typescript // multiple configs this.oidcSecurityService.preloadAuthWellKnownDocument('configId').subscribe((authWellKnown)=> ... ); ``` -------------------------------- ### preloadAuthWellKnownDocument() - Single Config Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of explicitly loading well-known endpoints for a single configuration. ```typescript // single config this.oidcSecurityService.preloadAuthWellKnownDocument().subscribe((authWellKnown)=> ... ); ``` -------------------------------- ### Local logoff Source: https://angular-auth-oidc-client.com/docs/documentation/login-logout Example of using the `logoffLocal` method to reset the local session without server interaction. ```typescript logoffLocal() { this.oidcSecurityService.logoffLocal(); } ``` -------------------------------- ### checkAuthIncludingServer (first config) Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of checking authentication status including server verification for the first or only config. ```typescript this.oidcSecurityService.checkAuthIncludingServer().subscribe(/*...*/); ``` -------------------------------- ### authorizeWithPopUp Example 2 Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Advanced usage of authorizeWithPopUp with custom authentication options and a specific configuration ID. ```typescript const authOptions = { customParams: { some: 'params', }, urlHandler: () => { /* ... */ }, redirectUrl: '/path-to/custom-popup-login-page.html', }; this.oidcSecurityService .authorizeWithPopUp(authOptions, null, 'configId') .subscribe(({ isAuthenticated, userData, accessToken, idToken, configId }) => { // ...use data }); ``` -------------------------------- ### Code flow PKCE with refresh tokens Source: https://angular-auth-oidc-client.com/docs/samples Demonstrates the OpenID Connect code flow with PKCE, including the use of refresh tokens for session management and logout. ```typescript Code ``` -------------------------------- ### Configuring secureRoutes with provideHttpClient Source: https://angular-auth-oidc-client.com/docs/documentation/interceptors This example demonstrates how to configure secureRoutes to specify which URLs should include the authorization header when using the authInterceptor. ```typescript export const appConfig: ApplicationConfig = { providers: [ provideHttpClient(withInterceptors([authInterceptor()])), provideAuth({ config: { // ... secureRoutes: ['https://my-secure-url.com/', 'https://my-second-secure-url.com/'], }, }), ], }; ``` -------------------------------- ### getUserData() - Specific Config ID Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of getting user data for a specific configuration by its ID. ```typescript // user data for this specific config this.oidcSecurityService.getUserData('configId').subscribe((data)=> ... ); ``` -------------------------------- ### checkAuthIncludingServer (specific config) Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of checking authentication status including server verification for a specific configuration. ```typescript this.oidcSecurityService.checkAuthIncludingServer('configId').subscribe(/*...*/); ``` -------------------------------- ### getUserData() - Single or First Config Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of getting user data for a single configuration, or the first one if multiple are configured. ```typescript // one config or the first one in case of multiple or null this.oidcSecurityService.getUserData().subscribe((data)=> ... ); ``` -------------------------------- ### logoff Example 2 Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Usage of logoff with custom logout authentication options and a specific configuration ID. ```typescript const authOptions = { customParams: { some: 'params', }, urlHandler: () => { /* ... */ }, }; this.oidcSecurityService.logoff('configId', authOptions).subscribe((result) => console.log(result)); ``` -------------------------------- ### Custom Popup Login Page Source: https://angular-auth-oidc-client.com/docs/documentation/login-logout Example of a custom HTML page for popup login, which posts the authentication result to the opener. ```html Transmitting authentication result ... (this popup will be closed automatically). ``` -------------------------------- ### Providing a Custom Storage Service (Old vs New) Source: https://angular-auth-oidc-client.com/docs/migrations/v13-to-v14 Compares the old method of providing a custom storage service via AuthModule.forRoot with the new method using Angular's dependency injection. ```typescript @NgModule({ imports: [ // ... AuthModule.forRoot({ config: { storage: new CustomStorage() } }) ], // ... }) ``` ```typescript @NgModule({ imports: [ AuthModule.forRoot({ config: { // ... }, }), ], providers: [{ provide: AbstractSecurityStorage, useClass: MyStorageService }], exports: [AuthModule], }) export class AuthConfigModule {} ``` -------------------------------- ### Get Access Token Source: https://angular-auth-oidc-client.com/docs/documentation/using-access-tokens Get the access token by calling the method getAccessToken() on the OidcSecurityService. ```typescript this.oidcSecurityService.getAccessToken().subscribe(at => ...); ``` -------------------------------- ### stsCallback$ Usage Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of how to assign the stsCallback$ observable to a component property. ```typescript this.stsCallback$ = this.oidcSecurityService.stsCallback$; ``` -------------------------------- ### checkSessionChanged$ Usage Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of how to assign the checkSessionChanged$ observable to a component property. ```typescript this.checkSessionChanged$ = this.oidcSecurityService.checkSessionChanged$; ``` -------------------------------- ### isLoading$ Usage Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of how to assign the isLoading$ observable to a component property. ```typescript this.isLoading$ = this.oidcSecurityService.isLoading$; ``` -------------------------------- ### New App Module Configuration Source: https://angular-auth-oidc-client.com/docs/migrations/v10-to-v11 This code snippet shows the new way of configuring the AppModule for authentication in version 11, using `withConfig`. ```typescript // imports import { NgModule, APP_INITIALIZER } from '@angular/core'; import { AuthModule, OidcConfigService } from 'angular-auth-oidc-client'; export function configureAuth(oidcConfigService: OidcConfigService) { return () => oidcConfigService.withConfig({ stsServer: 'https://localhost:44318', redirectUrl: window.location.origin, postLogoutRedirectUri: 'https://localhost:44395/unauthorized', clientId: 'angularclient2', scope: 'dataEventRecords openid profile email', responseType: 'code', silentRenew: true, silentRenewUrl: `${window.location.origin}/silent-renew.html`, renewTimeBeforeTokenExpiresInSeconds: 10, logLevel: LogLevel.Debug, postLoginRoute: '/dm', forbiddenRoute: '/unauthorized', unauthorizedRoute: '/unauthorized', historyCleanupOff: true, }); } @NgModule({ imports: [AuthModule.forRoot()], // declarations, etc. providers: [ OidcConfigService, { provide: APP_INITIALIZER, useFactory: configureAuth, deps: [OidcConfigService], multi: true, }, ], }) export class AppModule {} ``` -------------------------------- ### getRefreshToken (specific config) Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of retrieving the refresh token for a specific configuration. ```typescript this.oidcSecurityService.getRefreshToken('configId').subscribe(/*...*/); ``` -------------------------------- ### getRefreshToken (first config) Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of retrieving the refresh token for the first or only configuration. ```typescript this.oidcSecurityService.getRefreshToken().subscribe(/*...*/); ``` -------------------------------- ### getIdToken (specific config) Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of retrieving the ID token for a specific configuration. ```typescript this.oidcSecurityService.getIdToken('configId').subscribe(/*...*/); ``` -------------------------------- ### Load config from HTTP (async) Source: https://angular-auth-oidc-client.com/docs/documentation/configuration If you want to load the config from HTTP and then map it to the interface the library provides you can use the `StsConfigHttpLoader` and pass it with the `loader` property. ```typescript import { provideAuth, StsConfigHttpLoader, StsConfigLoader } from 'angular-auth-oidc-client'; export const httpLoaderFactory = (httpClient: HttpClient) => { const config$ = httpClient.get(`https://...`).pipe( map((customConfig: any) => { return { authority: customConfig.authority, /* Your config mapping here */ }; }) ); return new StsConfigHttpLoader(config$); }; export const appConfig: ApplicationConfig = { providers: [ provideAuth({ loader: { provide: StsConfigLoader, useFactory: httpLoaderFactory, deps: [HttpClient], }, }), ], }; ``` -------------------------------- ### Basic Login Source: https://angular-auth-oidc-client.com/docs/documentation/login-logout Initiates the login process by calling the authorize() method. ```typescript private readonly oidcSecurityService = inject(OidcSecurityService); // ... this.oidcSecurityService.authorize(); ``` -------------------------------- ### New Module Configuration (v11) Source: https://angular-auth-oidc-client.com/docs/migrations/v10-to-v11 This code snippet demonstrates the updated module configuration in version 11, utilizing RxJS operators and a dedicated factory function for configuring authentication. ```typescript import { NgModule, APP_INITIALIZER } from '@angular/core'; import { HttpClient, HttpClientModule } from '@angular/common/http'; import { AuthModule, OidcConfigService } from 'angular-auth-oidc-client'; import { map, switchMap } from 'rxjs/operators'; export function configureAuth( oidcConfigService: OidcConfigService, httpClient: HttpClient ) { const setupAction$ = httpClient .get(`${window.location.origin}/api/ClientAppSettings`) .pipe( map((customConfig) => { return { stsServer: customConfig.stsServer, redirectUrl: customConfig.redirect_url, clientId: customConfig.client_id, responseType: customConfig.response_type, scope: customConfig.scope, postLogoutRedirectUri: customConfig.post_logout_redirect_uri, startCheckSession: customConfig.start_checksession, silentRenew: true, silentRenewUrl: customConfig.redirect_url + '/silent-renew.html', postLoginRoute: customConfig.startup_route, forbiddenRoute: customConfig.forbidden_route, unauthorizedRoute: customConfig.unauthorized_route, logLevel: 0, // LogLevel.Debug, // customConfig.logLevel maxIdTokenIatOffsetAllowedInSeconds: customConfig.max_id_token_iat_offset_allowed_in_seconds, historyCleanupOff: true, }; }), switchMap((config) => oidcConfigService.withConfig(config)) ); return () => setupAction$.toPromise(); } @NgModule({ imports: [ HttpClientModule, AuthModule.forRoot(), // ... ], // ... providers: [ OidcConfigService, { provide: APP_INITIALIZER, useFactory: configureAuth, deps: [OidcConfigService, HttpClient], multi: true, }, ], bootstrap: [AppComponent], }) export class AppModule {} ``` -------------------------------- ### AppComponent - Old vs New Source: https://angular-auth-oidc-client.com/docs/migrations/v10-to-v11 Comparison of the AppComponent implementation before and after the v11 migration, showing changes in subscription handling and observable usage. ```typescript import { Component, OnInit, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-component', templateUrl: 'app.component.html', styleUrls: ['./app.component.scss'], }) export class AppComponent implements OnInit, OnDestroy { isAuthorizedSubscription: Subscription | undefined; isAuthorized = false; constructor(public oidcSecurityService: OidcSecurityService) { if (this.oidcSecurityService.moduleSetup) { this.doCallbackLogicIfRequired(); } else { this.oidcSecurityService.onModuleSetup.subscribe(() => { this.doCallbackLogicIfRequired(); }); } } ngOnInit() { this.isAuthorizedSubscription = this.oidcSecurityService .getIsAuthorized() .subscribe((isAuthorized: boolean) => { this.isAuthorized = isAuthorized; }); } ngOnDestroy(): void { if (this.isAuthorizedSubscription) { this.isAuthorizedSubscription.unsubscribe(); } } private doCallbackLogicIfRequired() { // Will do a callback, if the url has a code and state parameter. this.oidcSecurityService.authorizedCallbackWithCode( window.location.toString() ); } } ``` ```typescript import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; import { OidcSecurityService } from 'angular-auth-oidc-client'; @Component({ selector: 'app-component', templateUrl: 'app.component.html', styleUrls: ['./app.component.scss'], }) export class AppComponent implements OnInit { isAuthenticated$: Observable; constructor(public oidcSecurityService: OidcSecurityService) {} ngOnInit() { this.isAuthenticated$ = this.oidcSecurityService.isAuthenticated$; this.oidcSecurityService .checkAuth() .subscribe((isAuthenticated) => console.log('app authenticated', isAuthenticated) ); } } ``` -------------------------------- ### Manual Auth Check Source: https://angular-auth-oidc-client.com/docs/documentation/configuration Example of manually calling `OidcSecurityService.checkAuth()` in `app.component.ts` if `withAppInitializerAuthCheck` is omitted. ```typescript @Component() export class AppComponent implements OnInit { private readonly oidcSecurityService = inject(OidcSecurityService); ngOnInit(): void { this.oidcSecurityService.checkAuth().subscribe(({ isAuthenticated, accessToken }) => { console.log('app authenticated', isAuthenticated); console.log(`Current access token is '${accessToken}'`); }); } } ``` -------------------------------- ### authorize New configId Parameter Source: https://angular-auth-oidc-client.com/docs/migrations/v11-to-v12 Shows that the `authorize(...)` method now requires `configId` as the first parameter due to the introduction of multiple configurations. ```typescript const authOptions = {...} this.oidcSecurityService.authorize(authOptions) ``` ```typescript const authOptions = {...} const configIdOrNull = ./*...*/; this.oidcSecurityService.authorize(configIdOrNull, authOptions) ``` -------------------------------- ### Login with ConfigId Source: https://angular-auth-oidc-client.com/docs/documentation/login-logout Selects a specific configuration using the configId parameter for login. ```typescript login() { this.oidcSecurityService.authorize('configId'); } ``` -------------------------------- ### logoffAndRevokeTokens Example 1 Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Basic usage of logoffAndRevokeTokens to log out the user and revoke tokens. ```typescript this.oidcSecurityService.logoffAndRevokeTokens().subscribe(/* ... */); ``` -------------------------------- ### Custom Parameters in NgModule Configuration Source: https://angular-auth-oidc-client.com/docs/documentation/custom-parameters Illustrates how to configure custom parameters when using AuthModule.forRoot. ```typescript AuthModule.forRoot({ config: { authority: '', customParamsAuthRequest: { response_mode: 'fragment', prompt: 'consent', }, }, }), ``` -------------------------------- ### isAuthenticated - Old vs New Source: https://angular-auth-oidc-client.com/docs/migrations/v10-to-v11 Demonstrates the change in how to subscribe to the authentication status, from getIsAuthorized() to isAuthenticated$. ```typescript this.oidcSecurityService .getIsAuthorized() .subscribe((isAuthenticated: boolean) => { // work with `isAuthenticated` }); ``` ```typescript this.oidcSecurityService.isAuthenticated$.subscribe( (isAuthenticated: boolean) => { // work with `isAuthenticated` } ); ``` -------------------------------- ### logoffAndRevokeTokens Example 2 Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Usage of logoffAndRevokeTokens with custom authentication options and a specific configuration ID. ```typescript const authOptions = { customParams: { some: 'params', }, urlHandler: () => { /* ... */ }, }; this.oidcSecurityService.logoffAndRevokeTokens('configId', authOptions).subscribe(/* ... */); ``` -------------------------------- ### Using multiple HTTP configs Source: https://angular-auth-oidc-client.com/docs/documentation/configuration The HTTP loader also supports multiple configs. ```typescript import { provideAuth, StsConfigHttpLoader, StsConfigLoader } from 'angular-auth-oidc-client'; export const httpLoaderFactory = (httpClient: HttpClient) => { const config1$ = httpClient.get(`https://...`).pipe( map((customConfig: any) => { return { authority: customConfig.authority, /* Your config mapping here */ }; }) ); const config2$ = httpClient.get(`https://...`).pipe( map((customConfig: any) => { return { authority: customConfig.authority, /* Your config mapping here */ }; }) ); return new StsConfigHttpLoader([config1$, config2$]); }; export const appConfig: ApplicationConfig = { providers: [ provideAuth({ loader: { provide: StsConfigLoader, useFactory: httpLoaderFactory, deps: [HttpClient], }, }), ], }; ``` -------------------------------- ### isAuthenticated (specific config) Source: https://angular-auth-oidc-client.com/docs/documentation/public-api Example of checking authentication status for a specific configuration using its ID. ```typescript this.oidcSecurityService.isAuthenticated('configId').subscribe((isAuthenticated)=> ... ); ```