Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

ruve-angular-oauth2-oidc

manfredsteyer15MIT5.0.2TypeScript support: included

Support for OAuth 2 and OpenId Connect (OIDC) in Angular.

readme

angular-oauth2-oidc

Support for OAuth 2 and OpenId Connect (OIDC) in Angular.

OIDC Certified Logo

Credits

Resources

Tested Environment

Successfully tested with Angular 7 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 6: Use Version 4.x of this library. Version 4.x was tested with Angular 6. You can also try the newer version 5.x of this library which has a much smaller bundle size.

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).

Release Cycle

  • We plan one major release for each Angular version
    • Will contain new features
    • Will contain bug fixes and PRs
  • Critical Bugfixes on demand

Contributions

  • Feel free to file pull requests
  • The closed issues contain some ideas for PRs and enhancements (see labels)

Features

  • Logging in via OAuth2 and OpenId Connect (OIDC) Implicit Flow (where a user is redirected to Identity Provider)
  • "Logging in" via Password Flow (where a 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

Sample-Auth-Server

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

Installing

npm i angular-oauth2-oidc --save

Importing the NgModule

import { HttpClientModule } from '@angular/common/http';
import { OAuthModule } from 'angular-oauth2-oidc';
// etc.

@NgModule({
  imports: [ 
    // etc.
    HttpClientModule,
    OAuthModule.forRoot()
  ],
  declarations: [
    AppComponent,
    HomeComponent,
    // etc.
  ],
  bootstrap: [
    AppComponent 
  ]
})
export class AppModule {
}

Configuring for Implicit Flow

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();
    }
}

Implementing a Login Form

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>

Skipping the Login Form

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.

Calling a Web API with an Access Token

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
    }
})

Routing

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.

More Documentation

See the documentation for more information about this library.

Tutorials

changelog

Changelog

Features

  • update project to Angular 16 (b999024)

Bug Fixes

  • #728 (51e438a), closes /github.com/manfredsteyer/angular-oauth2-oidc/issues/728#issuecomment-808969225
  • clear location.hash only if it is present (c2b2753), closes #970
  • clock skew bug (f30098d)
  • correctly handle ? and & in location replacements (70fd826)
  • correctly use clockSkew for hasValid[Access|Id]Token (68238fb)
  • Disable nonce validation for id token for e2e tests (f5bd96c)
  • fix scope/state removal for implicit flow with hash (9e257d0)
  • in code flow pass options to error handler (c9a2c55), closes #972
  • issue with sha256 and prod build #1120 (b44e19a)
  • js-sha256: wrap logic in a function to prevent optimizer destroy lib (ae26fba)
  • jwks: update jsrsasign dependency to 10.2.0 (a05bd8a), closes #1061
  • multiplying calls to token endpoint in code flow (59f65d2)
  • Refresh tokens with a plus sign get corrupted before sending to token endpoint (2204c5a)
  • revoketokenandlogout: 'customParameters' should accept boolean (9761bad)
  • While Using POPUP mode, we click on login button multiple time it opens multiple popup instead of focusing already opened (bbff95b)

12.0.0 (2021-07-16)

Bug Fixes

Features

10.0.0 (2020-06-30)

  • chore: increase version in package.json (84d95a7)
  • chore: make version 9.2 ready (415e053)
  • chore(deps): bump jsrsasign from 8.0.12 to 8.0.19 (4def1c1)
  • chore(deps): bump websocket-extensions from 0.1.3 to 0.1.4 (cae715e)
  • chore(release): 9.2.1 (7a15194)
  • chore(release): 9.2.2 (40f5ae5)
  • chore(release): 9.3.0 (f42f943)
  • refactor: inline js-sha256 (ca435c0)
  • refactor: remove dep on contributer-table (b486546)
  • refactor: use esm for sha-256 (92ee76d)
  • feat(oauth-service): pass custom url params to logOut (4607d55)
  • feat(oauth-service): revokeTokenAndLogout with cust params (026dcb3)
  • 'disableAtHashCheck' by default if responseType is 'id_token' (169d749)
  • 825: (38c7c3f), closes #825

  • 825: (fb3afe4), closes #825

  • Fix issue with ambient type in constructor when running Universal with Ivy (9e95c73)
  • Fix typo in code-flow.md (1816e7b)
  • Replaced document by this.document #773 (678ff95), closes #773
  • response_types including 'code' gets a code_challenge (58a8132)
  • Update code-flow.md (5c5288c)
  • docs(readme): use our own idsvr (65c2b95)
  • fix: loadDiscoveryDocumentAndLogin should pass state into initLoginFlow (132c624)
  • fix(lib): copying LICENSE file to output build (e89aa6d)

10.0.0 (2020-06-30)

Bug Fixes

  • loadDiscoveryDocumentAndLogin should pass state into initLoginFlow (132c624)
  • lib: copying LICENSE file to output build (e89aa6d)

Features

  • oauth-service: pass custom url params to logOut (4607d55)
  • oauth-service: revokeTokenAndLogout with cust params (026dcb3)

10.0.0 (2020-06-30)

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

Features

  • automatic silent refresh: stopAutomaticRefresh stops all timers. (8ab853b)
  • code-flow: allow using implicit flow by setting useSilentRefresh to true (93902a5)
  • oauth-service: pass custom url params to logOut (4607d55)
  • oauth-service: revokeTokenAndLogout with cust params (026dcb3)
  • sample: also use new idsvr 4 for implicit flow demo to prevent issues with same site cookies (58c6354)
  • session checks: Session checks work now for code flow too. Pls see Docs for details. (4bf8901)
  • token-revocation: also revoke refresh_token (429ed2c)
  • remove jsrsasign dependancy (77cb37a)
  • Upgrade to angular 8 (31c6273)

Bug Fixes

  • loadDiscoveryDocumentAndLogin should pass state into initLoginFlow (132c624)
  • lib: copying LICENSE file to output build (e89aa6d)
  • revoketokenandlogout: explicit way to revoke an access token (c799ead)
  • sample: make sense of the guard (1cae011)
  • #687 (e2599e0)
  • code flow: Fixed code flow for IE 11 (0f03d39)
  • sample: use hash-based routing (3f44eca)
  • session state: save session_state also when using code flow (8fa99ff)
  • state: passing an url with a querystring as the state, e. g. url?x=1 (71b705c)
  • missing HttpModule dependency (7eac8ae)
  • run tokensetup outside ngzone (07bb62d)
  • typo (3d331f2)

9.2.2 (2020-05-09)

9.2.1 (2020-04-23)

9.2.0 (2020-03-28)

Features

  • revoketokenandlogout: explicit way to revoke an access token according to RFC 7009 (c799ead)

  • token-revocation: also revoke refresh_token (429ed2c)

Bug Fixes

  • sample: make sense of the guard (1cae011)

9.1.0 (2020-03-23)

Features

  • automatic silent refresh: stopAutomaticRefresh stops all timers. (8ab853b)
  • code-flow: allow using silent refresh by setting useSilentRefresh to true (93902a5)
  • sample: Also use new Identity Server 4 for implicit flow demo to prevent issues with same site cookies (58c6354)
  • session checks: Session checks work now for code flow too. Please see docs for details. (4bf8901)

Bug Fixes

  • code flow: Fixed code flow for IE 11 (0f03d39)
  • sample: use hash-based routing (3f44eca)
  • session state: save session_state also when using code flow (8fa99ff)
  • state: passing an url with a querystring as the state, e. g. url?x=1 (71b705c)
  • #687 (e2599e0)
  • missing HttpModule dependency (7eac8ae)
  • run tokensetup outside ngzone (07bb62d)
  • typo (3d331f2)

Pull Requests

  • Update sample app and silent-refresh.html script #755, linjie997
  • Add optional state parameter for logout, pmccloghrylaing
  • fix customHashFragment usage in tryLoginCodeFlow, roblabat
  • replace document with injectionToken #741, d-moos
  • Support predefined custom parameters extraction from the TokenResponse, vdveer
  • Fixed not working silent refresh when using 'code' #735, ErazerBrecht

Thanks

Big Thanks to all contributers: Brecht Carlier, Daniel Moos, Jie Lin, Manfred Steyer, Phil McCloghry-Laing, robin labat, vdveer

Also, big thanks to jeroenheijmans for doing an awesome job with moderating and analyzing the issues!