Support for OAuth 2 and OpenId Connect (OIDC) in Angular.
- generator-angular2-library for scaffolding an Angular library
- jsrasign for validating token signature and for hashing
- Identity Server (used for testing with an .NET/.NET Core Backend)
- Keycloak (Redhat) for testing with Java
-
Sources and Sample: https://github.com/manfredsteyer/angular-oauth2-oidc
-
Source Code Documentation https://manfredsteyer.github.io/angular-oauth2-oidc/docs
Successfully tested with Angular 6 and its Router, PathLocationStrategy as well as HashLocationStrategy and CommonJS-Bundling via webpack. At server side we've used IdentityServer (.NET/ .NET Core) and Redhat's Keycloak (Java).
Angular 5.x or 4.3: If you need support for Angular < 6 (4.3 to 5.x) you can download the former version 3.1.4 (npm i angular-oauth2-oidc@^3 --save).
- One major release for each Angular version
- Will contain new features
- Will contain bug fixes and PRs
- Critical Bugfixes on a regular basis
- Feel free to file pull requests
- The closed issues contain some ideas for PRs and enhancements (see labels)
- Logging in via OAuth2 and OpenId Connect (OIDC) Implicit Flow (where user is redirected to Identity Provider)
- "Logging in" via Password Flow (where user enters their password into the client)
- Token Refresh for Password Flow by using a Refresh Token
- Automatically refreshing a token when/some time before it expires
- Querying Userinfo Endpoint
- Querying Discovery Document to ease configuration
- Validating claims of the id_token regarding the specs
- Hook for further custom validations
- Single-Sign-Out by redirecting to the auth-server's logout-endpoint
You can use the OIDC-Sample-Server mentioned in the samples for Testing. It assumes, that your Web-App runs on http://localhost:8080.
Username/Password: max/geheim
clientIds:
- spa-demo (implicit flow)
- demo-resource-owner (resource owner password flow)
redirectUris:
- localhost:[8080-8089|4200-4202]
- localhost:[8080-8089|4200-4202]/index.html
- localhost:[8080-8089|4200-4202]/silent-refresh.html
npm i angular-oauth2-oidc --save
import { OAuthModule } from 'angular-oauth2-oidc';
[...]
@NgModule({
imports: [
[...]
HttpModule,
OAuthModule.forRoot()
],
declarations: [
AppComponent,
HomeComponent,
[...]
],
bootstrap: [
AppComponent
]
})
export class AppModule {
}
This section shows how to implement login leveraging implicit flow. This is the OAuth2/OIDC flow best suitable for Single Page Application. It sends the user to the Identity Provider's login page. After logging in, the SPA gets tokens. This also allows for single sign on as well as single sign off.
To configure the library the following sample uses the new configuration API introduced with Version 2.1. Hence, the original API is still supported.
import { AuthConfig } from 'angular-oauth2-oidc';
export const authConfig: AuthConfig = {
// Url of the Identity Provider
issuer: 'https://steyer-identity-server.azurewebsites.net/identity',
// URL of the SPA to redirect the user to after login
redirectUri: window.location.origin + '/index.html',
// The SPA's id. The SPA is registerd with this id at the auth-server
clientId: 'spa-demo',
// set the scope for the permissions the client should request
// The first three are defined by OIDC. The 4th is a usecase-specific one
scope: 'openid profile email voucher',
}
Configure the OAuthService with this config object when the application starts up:
import { OAuthService } from 'angular-oauth2-oidc';
import { JwksValidationHandler } from 'angular-oauth2-oidc';
import { authConfig } from './auth.config';
import { Component } from '@angular/core';
@Component({
selector: 'flight-app',
templateUrl: './app.component.html'
})
export class AppComponent {
constructor(private oauthService: OAuthService) {
this.configureWithNewConfigApi();
}
private configureWithNewConfigApi() {
this.oauthService.configure(authConfig);
this.oauthService.tokenValidationHandler = new JwksValidationHandler();
this.oauthService.loadDiscoveryDocumentAndTryLogin();
}
}
After you've configured the library, you just have to call initImplicitFlow
to login using OAuth2/ OIDC.
import { Component } from '@angular/core';
import { OAuthService } from 'angular-oauth2-oidc';
@Component({
templateUrl: "app/home.html"
})
export class HomeComponent {
constructor(private oauthService: OAuthService) {
}
public login() {
this.oauthService.initImplicitFlow();
}
public logoff() {
this.oauthService.logOut();
}
public get name() {
let claims = this.oauthService.getIdentityClaims();
if (!claims) return null;
return claims.given_name;
}
}
The following snippet contains the template for the login page:
<h1 *ngIf="!name">
Hallo
</h1>
<h1 *ngIf="name">
Hallo, {{name}}
</h1>
<button class="btn btn-default" (click)="login()">
Login
</button>
<button class="btn btn-default" (click)="logoff()">
Logout
</button>
<div>
Username/Passwort zum Testen: max/geheim
</div>
If you don't want to display a login form that tells the user that they are redirected to the identity server, you can use the convenience function this.oauthService.loadDiscoveryDocumentAndLogin();
instead of this.oauthService.loadDiscoveryDocumentAndTryLogin();
when setting up the library.
This directly redirects the user to the identity server if there are no valid tokens.
Pass this Header to the used method of the Http
-Service within an Instance of the class Headers
:
var headers = new Headers({
"Authorization": "Bearer " + this.oauthService.getAccessToken()
});
If you are using the new HttpClient
, use the class HttpHeaders
instead:
var headers = new HttpHeaders({
"Authorization": "Bearer " + this.oauthService.getAccessToken()
});
Since 3.1 you can also automate this task by switching sendAccessToken
on and by setting allowedUrls
to an array with prefixes for the respective urls. Use lower case for the prefixes.
OAuthModule.forRoot({
resourceServer: {
allowedUrls: ['http://www.angular.at/api'],
sendAccessToken: true
}
})
If you use the PathLocationStrategy
(which is on by default) and have a general catch-all-route (path: '**'
) you should be fine. Otherwise look up the section Routing with the HashStrategy
in the documentation.
See the documentation for more information about this library.