Angular Lib for OpenID Connect & OAuth2
npm install angular-auth-oidc-clientng add support
ng add the library.
shell
ng add angular-auth-oidc-client
`
And answer the questions. A module will be created which encapsulates your configuration.
!angular-auth-oidc-client schematics
$3
Navigate to the level of your package.json and type
`shell
npm install angular-auth-oidc-client
`
or with yarn
`shell
yarn add angular-auth-oidc-client
`
Documentation
Read the docs here
Samples
Explore the Samples here
Quickstart
For the example of the Code Flow. For further examples please check the Samples Section.
> If you have done the installation with the schematics, these modules and files should be available already!
$3
Import the AuthModule in your module.
`ts
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 {}
`
And call the method checkAuth() from your app.component.ts. The method checkAuth() is needed to process the redirect from your Security Token Service and set the correct states. This method must be used to ensure the correct functioning of the library.
`ts
import { Component, OnInit, inject } from '@angular/core';
import { OidcSecurityService } from 'angular-auth-oidc-client';
@Component({
/.../
})
export class AppComponent implements OnInit {
private readonly oidcSecurityService = inject(OidcSecurityService);
ngOnInit() {
this.oidcSecurityService.checkAuth().subscribe((loginResponse: LoginResponse) => {
const { isAuthenticated, userData, accessToken, idToken, configId } = loginResponse;
/.../
});
}
login() {
this.oidcSecurityService.authorize();
}
logout() {
this.oidcSecurityService.logoff().subscribe((result) => console.log(result));
}
}
`
$3
You can get the access token by calling the method getAccessToken() on the OidcSecurityService
`ts
const token = this.oidcSecurityService.getAccessToken().subscribe(...);
`
And then you can use it in the HttpHeaders
`ts
import { HttpHeaders } from '@angular/common/http';
const token = this.oidcSecurityServices.getAccessToken().subscribe((token) => {
const httpOptions = {
headers: new HttpHeaders({
Authorization: 'Bearer ' + token,
}),
};
});
`
You can use the built in interceptor to add the accesstokens to your request
`ts
AuthModule.forRoot({
config: {
// ...
secureRoutes: ['https://my-secure-url.com/', 'https://my-second-secure-url.com/'],
},
}),
`
`ts
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
],
``