angular-oauth2-oidc

repository·master·Indexed 24 days ago

https://github.com/manfredsteyer/angular-oauth2-oidc

An Angular library providing support for OAuth 2 and OpenID Connect (OIDC), including Code Flow with PKCE, Implicit Flow, and Password Flow. It features integration with providers like Auth0 and Azure AD, automatic access token attachment for Web APIs, and support for Angular Standalone Components (v14+) and NgModules. Version 22.0.0.

Tokens
25K
Snippets
63
Records
117
Agent score
84%

What's inside angular-oauth2-oidc

  1. Use a redirect URI with an initial route to avoid HashStrategy issues

    master

    An alternative to disabling initial navigation is to provide a redirectUri that already includes the desired initial route in the hash. When the router sees the route already present in the hash, it will not override it, allowing the library to read the tokens.

    http://localhost:8080/#/home
  2. Token refresh requirements for Session Checks

    master

    When session checks detect a change, the library performs a token refresh to synchronize the local state with the current session information. Depending on your authentication flow, you must ensure refresh capabilities are configured:

    If using refresh tokens, ensure your Auth Server binds the token lifetime to the session lifetime.

  3. Compatibility with OAuth2 and OpenID Connect Authorization Servers

    master

    The angular-oauth2-oidc library follows the OAuth2 and OpenID Connect (OIDC) specifications. As a result, it is designed to be compatible with any authorization server that adheres to these standards.

    Note that while the library is spec-compliant, some authorization servers may exhibit unique behaviors or require specific settings. When integrating with a particular provider, you may need to adjust your configuration to accommodate these non-standard implementations.

  4. Enable Session Checks to detect Identity Provider sign-out

    master

    Starting from version 2.1, you can detect when a user signs out from the Identity Provider (IdP) using the OpenID Connect Session Management 1.0 specification.

    When sessionChecksEnabled is set to true:

    1. The library automatically ends your local session by calling logOut (deleting current tokens).
    2. The library emits a session_terminated event.

    Note: This feature requires that your Identity Provider supports OpenID Connect Session Management.

    import { AuthConfig } from 'angular-oauth2-oidc';
    
    export const authConfig: AuthConfig = {
      issuer: 'https://steyer-identity-server.azurewebsites.net/identity',
      redirectUri: window.location.origin + '/index.html',
      silentRefreshRedirectUri: window.location.origin + '/silent-refresh.html',
      clientId: 'spa-demo',
      scope: 'openid profile email voucher',
    
      // Activate Session Checks:
      sessionChecksEnabled: true,
    }
  5. Handle successful login with the onTokenReceived callback

    master

    When performing a login using tryLogin, you can provide an onTokenReceived callback function within the options object. This callback is triggered immediately after a successful login, once the library has received the access_token and (if requested) the id_token. If an id_token was provided, the library automatically validates it before the callback is executed. The callback receives a context object containing the token information.

    this.oauthService.tryLogin({
        onTokenReceived: context => {
            //
            // Output just for purpose of demonstration
            // Don't try this at home ... ;-)
            //
            console.debug("logged in");
            console.debug(context);
        }
    });
  6. Bootstrap the library to fetch tokens

    master

    When bootstrapping your application, you must perform two steps to ensure the library is configured and attempts to process the login callback to fetch tokens:

    1. Call configure() with your AuthConfig.
    2. Call loadDiscoveryDocumentAndTryLogin() to fetch the OIDC discovery document and attempt to handle the login redirect.
    this.oauthService.configure(authCodeFlowConfig);
    this.oauthService.loadDiscoveryDocumentAndTryLogin();
  7. Initialize Login and Discovery

    master

    After configuring the service, you must call configure() and loadDiscoveryDocumentAndTryLogin() during application bootstrapping. To initialize the specific code flow, use initCodeFlow(). Alternatively, initLoginFlow() automatically chooses between code and implicit flow based on your configuration.

    // During bootstrapping
    this.oauthService.configure(authCodeFlowConfig);
    this.oauthService.loadDiscoveryDocumentAndTryLogin();
    
    // To trigger the flow
    this.oauthService.initCodeFlow();
    // OR
    this.oauthService.initLoginFlow();
  8. Install angular-oauth2-oidc-jwks for Implicit Flow

    master

    Starting from version 9, JwksValidationHandler has been moved to a separate library to improve tree shaking and reduce bundle sizes. If you are implementing the implicit flow, you must install the JWKS package separately.

    Note: This dependency is not required if you are using the code flow, which is the recommended flow for single-page applications.

    npm i angular-oauth2-oidc-jwks --save
  9. Monitor library state using OAuthService events

    master

    The library provides an Observable<OAuthEvent> via this.oauthService.events that publishes a stream of events as they occur. You can subscribe to this stream to react to lifecycle changes, such as token reception or configuration loading, or to log them for debugging purposes.

    this.oauthService.events.subscribe(e => console.log(e));
  10. Enable the default OAuth2 HttpInterceptor

    master

    Since version 3.1, the library includes a default HttpInterceptor that automatically attaches the access_token to requests sent to authorized resource servers and handles security-related errors (HTTP 401 and 403).

    To enable this, configure the resourceServer object within your OAuthModule.forRoot() call:

    1. Set sendAccessToken to true.
    2. Set allowedUrls to an array of URL prefixes. Note: Use lower case for the prefixes.
    OAuthModule.forRoot({
        resourceServer: {
            allowedUrls: ['http://www.angular.at/api'],
            sendAccessToken: true
        }
    })