Convert Figma logo to code with AI

damienbod logoangular-auth-oidc-client

npm package for OpenID Connect, OAuth Code Flow with PKCE, Refresh tokens, Implicit Flow

1,130
429
1,130
199

Top Related Projects

OpenID Connect (OIDC) and OAuth2 protocol support for browser-based JavaScript applications

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

OpenID Connect (OIDC) and OAuth2 protocol support for browser-based JavaScript applications

OAuth 2 / OpenID Connect Client API for JavaScript Runtimes

Quick Overview

Angular-auth-oidc-client is an OpenID Connect (OIDC) and OAuth2 library for Angular applications. It provides a robust implementation for authentication and authorization, supporting various OIDC and OAuth2 flows, including implicit flow and code flow with PKCE.

Pros

  • Easy integration with Angular applications
  • Supports multiple OIDC providers and configurations
  • Implements security best practices, including PKCE
  • Actively maintained with regular updates

Cons

  • Steep learning curve for developers new to OIDC concepts
  • Limited documentation for advanced use cases
  • Potential performance impact on larger applications
  • Some users report occasional issues with token refresh

Code Examples

  1. Basic configuration:
import { AuthModule } from 'angular-auth-oidc-client';

@NgModule({
  imports: [
    AuthModule.forRoot({
      config: {
        authority: 'https://your-authority.com',
        redirectUrl: window.location.origin,
        clientId: 'your-client-id',
        scope: 'openid profile email',
        responseType: 'code',
      },
    }),
  ],
})
export class AppModule {}
  1. Checking authentication status:
import { OidcSecurityService } from 'angular-auth-oidc-client';

export class AppComponent {
  constructor(public oidcSecurityService: OidcSecurityService) {}

  ngOnInit() {
    this.oidcSecurityService.checkAuth().subscribe(({ isAuthenticated }) => {
      console.log('App is authenticated', isAuthenticated);
    });
  }
}
  1. Initiating login:
import { OidcSecurityService } from 'angular-auth-oidc-client';

export class LoginComponent {
  constructor(private oidcSecurityService: OidcSecurityService) {}

  login() {
    this.oidcSecurityService.authorize();
  }
}

Getting Started

  1. Install the library:

    npm install angular-auth-oidc-client
    
  2. Import and configure the AuthModule in your app.module.ts:

    import { AuthModule } from 'angular-auth-oidc-client';
    
    @NgModule({
      imports: [
        AuthModule.forRoot({
          config: {
            authority: 'https://your-authority.com',
            redirectUrl: window.location.origin,
            clientId: 'your-client-id',
            scope: 'openid profile email',
            responseType: 'code',
          },
        }),
      ],
    })
    export class AppModule {}
    
  3. Use the OidcSecurityService in your components to handle authentication and authorization.

Competitor Comparisons

OpenID Connect (OIDC) and OAuth2 protocol support for browser-based JavaScript applications

Pros of oidc-client-js

  • Framework-agnostic, can be used with any JavaScript application
  • More mature and widely adopted in the community
  • Extensive documentation and examples available

Cons of oidc-client-js

  • Less Angular-specific features and integration
  • May require more manual configuration for Angular projects
  • Not actively maintained (last update was in 2021)

Code Comparison

oidc-client-js:

var settings = {
    authority: 'https://demo.identityserver.io/',
    client_id: 'implicit',
    redirect_uri: 'https://localhost:5000/callback.html',
    response_type: 'id_token token',
    scope: 'openid profile email api',
};
var mgr = new Oidc.UserManager(settings);

angular-auth-oidc-client:

@NgModule({
    imports: [
        AuthModule.forRoot({
            config: {
                authority: 'https://demo.identityserver.io',
                redirectUrl: window.location.origin,
                clientId: 'angular',
                scope: 'openid profile email api',
            },
        }),
    ],
})
export class AppModule {}

The code snippets demonstrate the configuration differences between the two libraries. oidc-client-js uses a more generic JavaScript approach, while angular-auth-oidc-client is specifically designed for Angular applications, offering a more integrated and type-safe configuration within the Angular module system.

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

Pros of angular-oauth2-oidc

  • More comprehensive documentation and examples
  • Support for multiple OAuth 2.0 flows, including implicit and code flow
  • Active community with frequent updates and contributions

Cons of angular-oauth2-oidc

  • Slightly more complex setup process
  • May have a steeper learning curve for beginners
  • Some users report occasional issues with token refresh

Code Comparison

angular-oauth2-oidc:

import { AuthConfig } from 'angular-oauth2-oidc';

export const authConfig: AuthConfig = {
  issuer: 'https://idsvr4.azurewebsites.net',
  redirectUri: window.location.origin + '/index.html',
  clientId: 'spa',
  scope: 'openid profile email api',
};

angular-auth-oidc-client:

import { OpenIdConfiguration } from 'angular-auth-oidc-client';

export const config: OpenIdConfiguration = {
  authority: 'https://idsvr4.azurewebsites.net',
  redirectUrl: window.location.origin,
  clientId: 'spa',
  scope: 'openid profile email api',
};

Both libraries offer similar functionality for implementing OAuth 2.0 and OpenID Connect in Angular applications. angular-oauth2-oidc provides more extensive documentation and supports multiple OAuth flows, making it suitable for complex scenarios. However, it may be slightly more challenging to set up initially. angular-auth-oidc-client offers a simpler setup process and may be more suitable for beginners or straightforward authentication requirements. The code comparison shows that both libraries use similar configuration objects, with minor differences in property names.

OpenID Connect (OIDC) and OAuth2 protocol support for browser-based JavaScript applications

Pros of oidc-client-ts

  • Framework-agnostic, can be used with any JavaScript framework
  • Smaller bundle size, focused solely on OIDC functionality
  • More active development and frequent updates

Cons of oidc-client-ts

  • Less Angular-specific features and integrations
  • May require more manual configuration for Angular projects
  • Fewer built-in guards and interceptors for Angular routing

Code Comparison

oidc-client-ts:

import { UserManager } from "oidc-client-ts";

const userManager = new UserManager(settings);
const user = await userManager.signinRedirect();

angular-auth-oidc-client:

import { OidcSecurityService } from 'angular-auth-oidc-client';

constructor(public oidcSecurityService: OidcSecurityService) {}
this.oidcSecurityService.authorize();

The oidc-client-ts library provides a more generic approach, while angular-auth-oidc-client offers Angular-specific implementations. oidc-client-ts requires manual instantiation of the UserManager, whereas angular-auth-oidc-client integrates more seamlessly with Angular's dependency injection system.

Both libraries serve the purpose of implementing OpenID Connect authentication, but they cater to different use cases. oidc-client-ts is more versatile for various JavaScript projects, while angular-auth-oidc-client is tailored specifically for Angular applications, providing a more integrated experience within the Angular ecosystem.

OAuth 2 / OpenID Connect Client API for JavaScript Runtimes

Pros of openid-client

  • Language-agnostic: Can be used with various programming languages and frameworks
  • More comprehensive OpenID Connect support, including advanced features
  • Actively maintained with frequent updates and improvements

Cons of openid-client

  • Steeper learning curve due to its broader scope and flexibility
  • Less Angular-specific optimizations and integrations
  • May require additional configuration for Angular projects

Code Comparison

angular-auth-oidc-client:

import { AuthModule } from 'angular-auth-oidc-client';

@NgModule({
  imports: [AuthModule.forRoot({
    config: { authority: 'https://example.com', clientId: 'client' }
  })]
})
export class AppModule {}

openid-client:

const { Issuer } = require('openid-client');

Issuer.discover('https://example.com')
  .then(issuer => {
    const client = new issuer.Client({
      client_id: 'client',
      client_secret: 'secret'
    });
  });

The angular-auth-oidc-client example shows a more Angular-specific implementation, while openid-client demonstrates a more generic approach that can be adapted to various environments. The openid-client example requires additional setup for Angular integration, but offers more flexibility for different use cases.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Angular Lib for OpenID Connect & OAuth2

Build Status npm npm npm code style: prettier Coverage Status

Secure your Angular app using the latest standards for OpenID Connect & OAuth2. Provides support for token refresh, all modern OIDC Identity Providers and more.

Acknowledgements

This library is certified by OpenID Foundation. (RP Implicit and Config RP)

Features

Installation

Ng Add

You can use the schematics and ng add the library.

ng add angular-auth-oidc-client

And answer the questions. A module will be created which encapsulates your configuration.

angular-auth-oidc-client schematics

Npm / Yarn

Navigate to the level of your package.json and type

 npm install angular-auth-oidc-client

or with yarn

 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!

Configuration

Import the AuthModule in your module.

import { NgModule } from '@angular/core';
import { AuthModule, LogLevel } from 'angular-auth-oidc-client';
// ...

@NgModule({
  // ...
  imports: [
    // ...
    AuthModule.forRoot({
      config: {
        authority: '<your authority address here>',
        redirectUrl: window.location.origin,
        postLogoutRedirectUri: window.location.origin,
        clientId: '<your 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.

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

Using the access token

You can get the access token by calling the method getAccessToken() on the OidcSecurityService

const token = this.oidcSecurityService.getAccessToken().subscribe(...);

And then you can use it in the HttpHeaders

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

AuthModule.forRoot({
  config: {
    // ...
    secureRoutes: ['https://my-secure-url.com/', 'https://my-second-secure-url.com/'],
  },
}),
 providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
  ],

Versions

Current Version is Version 18.x

License

MIT

Authors

NPM DownloadsLast 30 Days