@auth0/angular-jwt Documentation

repository·main·Indexed 25 days ago

https://github.com/auth0/angular2-jwt

A helper library for Angular applications (version 5.2.0) that provides an HttpInterceptor to automatically attach JSON Web Tokens (JWT) to HttpClient requests. It includes JwtModule for configuration of allowed domains and disallowed routes, and JwtHelperService for decoding tokens, checking expiration dates, and validating JWTs.

Tokens
3.7K
Snippets
9
Records
22
Agent score
82%

What's inside @auth0/angular-jwt

  1. Configure JwtModule in an NgModule-based application

    main

    To use the SDK in a traditional Angular application, import JwtModule and HttpClientModule. Use JwtModule.forRoot() to provide a configuration object containing:

    • tokenGetter: A function that returns the JWT string (e.g., from localStorage).
    • allowedDomains: An array of domains where the token should be attached.
    • disallowedRoutes: An array of specific routes where the token should NOT be attached.
    import { JwtModule } from "@auth0/angular-jwt";
    import { HttpClientModule } from "@angular/common/http";
    
    export function tokenGetter() {
      return localStorage.getItem("access_token");
    }
    
    @NgModule({
      bootstrap: [AppComponent],
      imports: [
        // ...
        HttpClientModule,
        JwtModule.forRoot({
          config: {
            tokenGetter: tokenGetter,
            allowedDomains: ["example.com"],
            disallowedRoutes: ["http://example.com/examplebadroute/"],
          },
        }),
      ],
    })
    export class AppModule {}
  2. Configure JwtModule with Standalone Components

    main

    When using bootstrapApplication for a standalone application, integrate the SDK using importProvidersFrom and ensure provideHttpClient is configured with withInterceptorsFromDi() to enable the library's interceptor.

    import { JwtModule } from "@auth0/angular-jwt";
    import { provideHttpClient, withInterceptorsFromDi } from "@angular/common/http";
    
    export function tokenGetter() {
      return localStorage.getItem("access_token");
    }
    
    bootstrapApplication(AppComponent, {
        providers: [
            // ...
            importProvidersFrom(
                JwtModule.forRoot({
                    config: {
                        tokenGetter: tokenGetter,
                        allowedDomains: ["example.com"],
                        disallowedRoutes: ["http://example.com/examplebadroute/"],
                    },
                }),
            ),
            provideHttpClient(
                withInterceptorsFromDi()
            ),
        ],
    });
  3. Use a custom options factory function with JWT_OPTIONS

    main

    If your tokenGetter function depends on a service or requires an asynchronous storage mechanism, you should use a custom factory function instead of passing a static config object to JwtModule.forRoot.

    To implement this:

    1. Import JWT_OPTIONS from @auth0/angular-jwt.
    2. Define a factory function that returns your configuration object (including tokenGetter and allowedDomains).
    3. Use JwtModule.forRoot with a jwtOptionsProvider that provides JWT_OPTIONS using useFactory and specifies any required services in the deps array.

    Important: If you define a jwtOptionsProvider, the standard config object in JwtModule.forRoot is ignored. You cannot use both configuration methods simultaneously.

    import { JwtModule, JWT_OPTIONS } from '@auth0/angular-jwt';
    import { TokenService } from './app.tokenservice';
    
    // Define the factory function
    export function jwtOptionsFactory(tokenService) {
      return {
        tokenGetter: () => {
          return tokenService.getAsyncToken();
        },
        allowedDomains: ["example.com"]
      }
    }
    
    @NgModule({
      imports: [
        JwtModule.forRoot({
          jwtOptionsProvider: {
            provide: JWT_OPTIONS,
            useFactory: jwtOptionsFactory,
            deps: [TokenService]
          }
        })
      ],
      providers: [TokenService]
    })
  4. Configure angular-jwt for Ionic 2+ using Ionic Storage

    main

    To retrieve a JWT asynchronously from Ionic's Storage, use a custom factory function via the JWT_OPTIONS provider. This allows the tokenGetter to return a Promise from the storage engine.

    Note: When using jwtOptionsProvider, the standard config object is ignored.

    import { JwtModule, JWT_OPTIONS } from '@auth0/angular-jwt';
    import { Storage } from '@ionic/storage';
    
    export function jwtOptionsFactory(storage) {
      return {
        tokenGetter: () => {
          return storage.get('access_token');
        },
        allowedDomains: ["example.com"]
      }
    }
    
    @NgModule({
      imports: [
        JwtModule.forRoot({
          jwtOptionsProvider: {
            provide: JWT_OPTIONS,
            useFactory: jwtOptionsFactory,
            deps: [Storage]
          }
        })
      ]
    })
  5. Install @auth0/angular-jwt

    main

    Install the library using npm or yarn to enable automatic JWT attachment to Angular HttpClient requests.

    # installation with npm
    npm install @auth0/angular-jwt
    
    # installation with yarn
    yarn add @auth0/angular-jwt
  6. Configure `JwtModule` options

    main

    Use JwtModule.forRoot() to configure how the SDK handles JWTs. Key configuration options include:

    • tokenGetter: A function that retrieves the token (e.g., from localStorage). It receives the HttpRequest as an argument, allowing for domain-specific token retrieval.
    • allowedDomains: An array of trusted domains. Tokens are only sent to these domains. Standard ports (80/443) do not require explicit port numbers, but non-standard ports (e.g., localhost:3001) must be included.
    • disallowedRoutes: An array of strings or regular expressions for routes where the authorization header should NOT be replaced. Use // as a prefix to ignore the protocol.
    • headerName: The name of the HTTP header to use (defaults to Authorization).
    • authScheme: The prefix for the token (defaults to Bearer ). Can be a string or a function that returns a string based on the HttpRequest.
    • throwNoTokenError: If true, throws an error if tokenGetter fails to return a token.
    • skipWhenExpired: If true, prevents the token from being sent if it is expired.
    JwtModule.forRoot({
      config: {
        tokenGetter: () => localStorage.getItem("access_token"),
        allowedDomains: ["localhost:3001", "foo.com"],
        disallowedRoutes: ["http://localhost:3001/auth/", "//foo.com/bar/baz"],
        headerName: "Your Header Name",
        authScheme: "Basic ",
        throwNoTokenError: true,
        skipWhenExpired: true,
      },
    });
  7. Implement a dynamic `authScheme`

    main

    If you need to change the authorization scheme (e.g., switching between Bearer and Basic ) based on the request, provide a function to the authScheme configuration option.

    JwtModule.forRoot({
      config: {
        authScheme: (request) => {
          if (request.url.includes("foo")) {
            return "Basic ";
          }
    
          return "Bearer ";
        },
      },
    });
  8. Automatic JWT attachment to HttpClient requests

    main

    Once configured, any request made via Angular's HttpClient to a domain specified in allowedDomains will automatically include the JWT in the Authorization header.

    import { HttpClient } from "@angular/common/http";
    
    export class AppComponent {
      constructor(public http: HttpClient) {}
    
      ping() {
        this.http.get("http://example.com/api/things").subscribe(
          (data) => console.log(data),
          (err) => console.log(err)
        );
      }
    }
  9. Implement a dynamic `tokenGetter`

    main

    You can use the HttpRequest object passed to tokenGetter to return different tokens based on the request URL. This is useful for applications interacting with multiple APIs that require different credentials.

    JwtModule.forRoot({
      config: {
        tokenGetter: (request) => {
          if (request.url.includes("foo")) {
            return localStorage.getItem("access_token_foo");
          }
    
          return localStorage.getItem("access_token");
        },
      },
    });
  10. Configure JwtInterceptor via JWT_OPTIONS

    main

    The JwtInterceptor is configured using the JWT_OPTIONS injection token. This interceptor automatically attaches JWTs to outgoing HttpClient requests based on the following configuration properties:

    • tokenGetter: A function that returns the token (string, null, or a Promise resolving to string/null). It can optionally receive the HttpRequest.
    • headerName: The name of the HTTP header to use (defaults to 'Authorization').
    • authScheme: The authentication scheme prefix (e.g., 'Bearer '). Can be a string or a function that returns a string based on the request.
    • allowedDomains: An array of strings or RegExps defining which domains are permitted to receive the token. The current window origin is allowed by default.
    • disallowedRoutes: An array of strings or RegExps defining specific routes that should not receive the token.
    • throwNoTokenError: If true, throws an error if the tokenGetter returns no token.
    • skipWhenExpired: If true, the interceptor will skip attaching the token if the token is expired.