### Install @auth0/angular-jwt with npm Source: https://github.com/auth0/angular2-jwt/blob/main/README.md Use npm to install the library for your Angular project. ```bash npm install @auth0/angular-jwt ``` -------------------------------- ### Install @auth0/angular-jwt with yarn Source: https://github.com/auth0/angular2-jwt/blob/main/README.md Use yarn to install the library for your Angular project. ```bash yarn add @auth0/angular-jwt ``` -------------------------------- ### Configure JwtModule.forRoot() in Root Module Source: https://context7.com/auth0/angular2-jwt/llms.txt Configure the JwtModule in your application's root module. This setup includes a tokenGetter function and specifies allowed domains for token transmission. ```typescript import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { JwtModule } from '@auth0/angular-jwt'; export function tokenGetter() { return localStorage.getItem('access_token'); } @NgModule({ imports: [ HttpClientModule, JwtModule.forRoot({ config: { tokenGetter: tokenGetter, allowedDomains: ['api.example.com', 'localhost:3001'], disallowedRoutes: ['http://api.example.com/auth/login'], headerName: 'Authorization', authScheme: 'Bearer ', throwNoTokenError: false, skipWhenExpired: false } }) ], bootstrap: [AppComponent] }) export class AppModule {} ``` -------------------------------- ### Making Authenticated HTTP Requests with Angular HttpClient Source: https://context7.com/auth0/angular2-jwt/llms.txt Angular's HttpClient automatically includes the JWT in requests to configured domains once the library is set up. No extra code is required for token attachment to GET, POST, PUT, or PATCH requests. ```typescript import { Component } from '@angular/core'; import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { catchError, throwError } from 'rxjs'; interface User { id: string; name: string; email: string; } @Component({ selector: 'app-user-service', template: `
{{ user.name }} ({{ user.email }})
` }) export class UserComponent { user: User | null = null; constructor(private http: HttpClient) {} loadUser(): void { // JWT is automatically attached to this request // Request headers: Authorization: Bearer this.http.get('https://api.example.com/user/profile') .pipe( catchError(this.handleError) ) .subscribe(user => { this.user = user; }); } updateUser(userData: Partial): void { // POST/PUT/PATCH requests also get the JWT automatically this.http.put('https://api.example.com/user/profile', userData) .subscribe(updatedUser => { this.user = updatedUser; }); } // Requests to disallowed routes don't include the JWT login(credentials: { email: string; password: string }): void { this.http.post<{ token: string }>('https://api.example.com/auth/login', credentials) .subscribe(response => { localStorage.setItem('access_token', response.token); }); } private handleError(error: HttpErrorResponse) { if (error.status === 401) { console.error('Authentication failed - token may be invalid or expired'); } return throwError(() => error); } } ``` -------------------------------- ### Get JWT Expiration Date using JwtHelperService Source: https://github.com/auth0/angular2-jwt/blob/main/API.md Retrieve the expiration date of the JWT using the `getTokenExpirationDate` method from `JwtHelperService`. This method returns a Date object or null if the token is invalid or has no expiration. ```typescript import { JwtHelperService } from '@auth0/angular-jwt'; // ... constructor(public jwtHelper: JwtHelperService) {} ngOnInit() { console.log(this.jwtHelper.getTokenExpirationDate()); // date } ``` -------------------------------- ### Configure JwtModule with Basic Token Getter Source: https://github.com/auth0/angular2-jwt/blob/main/API.md Set up the JwtModule with a token getter function that retrieves the access token from local storage. ```typescript JwtModule.forRoot({ config: { // ... tokenGetter: () => { return localStorage.getItem("access_token"); }, }, }); ``` -------------------------------- ### Configure Ionic Storage for TokenGetter Source: https://context7.com/auth0/angular2-jwt/llms.txt Configure the tokenGetter to return a Promise when using asynchronous storage like Ionic Storage. ```typescript import { NgModule } from '@angular/core'; import { JwtModule, JWT_OPTIONS } from '@auth0/angular-jwt'; import { Storage } from '@ionic/storage'; export function jwtOptionsFactory(storage: Storage) { return { tokenGetter: () => { return storage.get('access_token'); // Returns Promise }, allowedDomains: ['api.example.com'] }; } @NgModule({ imports: [ JwtModule.forRoot({ jwtOptionsProvider: { provide: JWT_OPTIONS, useFactory: jwtOptionsFactory, deps: [Storage] } }) ] }) export class AppModule {} ``` -------------------------------- ### Configure JwtModule with Standalone Components Source: https://github.com/auth0/angular2-jwt/blob/main/README.md For standalone components, use importProvidersFrom for JwtModule and provideHttpClient with withInterceptorsFromDi. ```typescript 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() ), ], }); ``` -------------------------------- ### Configure JwtModule for Standalone Components Source: https://context7.com/auth0/angular2-jwt/llms.txt Configure the JwtModule for standalone components using bootstrapApplication. This involves using importProvidersFrom and provideHttpClient. ```typescript import { bootstrapApplication } from '@angular/platform-browser'; import { importProvidersFrom } from '@angular/core'; import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http'; import { JwtModule } from '@auth0/angular-jwt'; import { AppComponent } from './app/app.component'; export function tokenGetter() { return localStorage.getItem('access_token'); } bootstrapApplication(AppComponent, { providers: [ importProvidersFrom( JwtModule.forRoot({ config: { tokenGetter: tokenGetter, allowedDomains: ['api.example.com'], disallowedRoutes: ['http://api.example.com/auth/'] } }) ), provideHttpClient(withInterceptorsFromDi()) ] }); ``` -------------------------------- ### JwtModule Configuration Options Source: https://github.com/auth0/angular2-jwt/blob/main/API.md Configuration options for JwtModule to customize token handling, domain restrictions, and header customization. ```APIDOC ## JwtModule Configuration Options ### `tokenGetter: function(HttpRequest): string` The `tokenGetter` is a function which returns the user's token. This function simply needs to make a retrieval call to wherever the token is stored. In many cases, the token will be stored in local storage or session storage. ```ts // ... JwtModule.forRoot({ config: { // ... tokenGetter: () => { return localStorage.getItem("access_token"); }, }, }); ``` If you have multiple tokens for multiple domains, you can use the `HttpRequest` passed to the `tokenGetter` function to get the correct token for each intercepted request. ```ts // ... JwtModule.forRoot({ config: { // ... tokenGetter: (request) => { if (request.url.includes("foo")) { return localStorage.getItem("access_token_foo"); } return localStorage.getItem("access_token"); }, }, }); ``` ### `allowedDomains: array` Authenticated requests should only be sent to domains you know and trust. Many applications make requests to APIs from multiple domains, some of which are not controlled by the developer. Since there is no way to know what the API being called will do with the information contained in the request, it is best to not send the user's token to all APIs in a blind fashion. List any domains you wish to allow authenticated requests to be sent to by specifying them in the `allowedDomains` array. **Note that standard http port 80 and https port 443 requests don't require a port to be specified. A port is only required in the allowed domains host name if you are authenticating against a non-standard port e.g. localhost:3001** ```ts // ... JwtModule.forRoot({ config: { // ... allowedDomains: ["localhost:3001", "foo.com", "bar.com"], }, }); ``` ### `disallowedRoutes: array` If you do not want to replace the authorization headers for specific routes, list them here. This can be useful if your initial auth route(s) are on an allowed domain and take basic auth headers. These routes need to be prefixed with the correct protocol (`http://`, `https://`). If you want to add a route to the list of disallowed routes regardless of the protocol, you can prefix it with `//`. ```ts // ... JwtModule.forRoot({ config: { // ... disallowedRoutes: [ "http://localhost:3001/auth/", "https://foo.com/bar/", "//foo.com/bar/baz", /localhost:3001\/foo\/far.*/, ], // strings and regular expressions }, }); ``` **Note:** If requests are sent to the same domain that is serving your Angular application, you do not need to add that domain to the `allowedDomains` array. However, this is only the case if you don't specify the domain in the `Http` request. For example, the following request assumes that the domain is the same as the one serving your app. It doesn't need to be allowed in this case. ```ts this.http.get('/api/things') .subscribe(...) ``` However, if you are serving your API at the same domain as that which is serving your Angular app **and** you are specifying that domain in `Http` requests, then it **does** need to be explicitely allowed. ```ts // Both the Angular app and the API are served at // localhost:4200 but because that domain is specified // in the request, it must be allowed this.http.get('http://localhost:4200/api/things') .subscribe(...) ``` ### `headerName: string` The default header name is `Authorization`. This can be changed by specifying a custom `headerName` which is to be a string value. ```ts // ... JwtModule.forRoot({ config: { // ... headerName: "Your Header Name", }, }); ``` ### `authScheme: string | function(HttpRequest): string` The default authorization scheme is `Bearer` followed by a single space. This can be changed by specifying a custom `authScheme`. You can pass a string which will prefix the token for each request. ```ts // ... JwtModule.forRoot({ config: { // ... authScheme: "Basic ", }, }); ``` If you want to change the auth scheme dynamically, or based on the request, you can configure a getter function which returns a string. ```ts // ... JwtModule.forRoot({ config: { // ... authScheme: (request) => { if (request.url.includes("foo")) { return "Basic "; } return "Bearer "; }, }, }); ``` ### `throwNoTokenError: boolean` Setting `throwNoTokenError` to `true` will result in an error being thrown if a token cannot be retrieved with the `tokenGetter` function. Defaults to `false`. ```ts // ... JwtModule.forRoot({ config: { // ... throwNoTokenError: true, }, }); ``` ``` -------------------------------- ### Configure JwtModule in AppModule Source: https://github.com/auth0/angular2-jwt/blob/main/README.md Import JwtModule and HttpClientModule, and configure JwtModule with a tokenGetter function and allowed domains. ```typescript 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 {} ``` -------------------------------- ### Configure JwtModule with Disallowed Routes Source: https://github.com/auth0/angular2-jwt/blob/main/API.md List specific routes (as strings or regular expressions) for which authorization headers should not be added. Routes can be prefixed with protocols or '//' to ignore protocol. ```typescript JwtModule.forRoot({ config: { // ... disallowedRoutes: [ "http://localhost:3001/auth/", "https://foo.com/bar/", "//foo.com/bar/baz", /localhost:3001\/foo\/far.*/, ], // strings and regular expressions }, }); ``` -------------------------------- ### Configure JwtModule with Dynamic Auth Scheme Source: https://github.com/auth0/angular2-jwt/blob/main/API.md Configure a getter function for `authScheme` that dynamically determines the authorization scheme based on the request URL. ```typescript JwtModule.forRoot({ config: { // ... authScheme: (request) => { if (request.url.includes("foo")) { return "Basic "; } return "Bearer "; }, }, }); ``` -------------------------------- ### Configure JWT for Ionic 2+ with Async Storage Source: https://github.com/auth0/angular2-jwt/blob/main/EXAMPLES.md Configure JWT for Ionic 2+ by using a custom factory function with Ionic's Storage for asynchronous token retrieval. Ensure the Storage service is listed in the deps array. ```typescript 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] } }) ] }) ``` -------------------------------- ### Making Authenticated HTTP Requests Source: https://context7.com/auth0/angular2-jwt/llms.txt Demonstrates how Angular's HttpClient automatically includes the JWT in requests to configured domains, simplifying authenticated API calls. ```APIDOC ## Making Authenticated HTTP Requests ### Description Once configured, Angular's HttpClient automatically includes the JWT in requests to allowed domains. No additional code is needed for token attachment. ### Method `HttpClient` methods (GET, POST, PUT, DELETE, etc.) ### Endpoint Any configured API endpoint that requires authentication. ### Parameters None directly for token attachment; the JWT is handled automatically. ### Request Example ```typescript // JWT is automatically attached to this request // Request headers: Authorization: Bearer this.http.get('https://api.example.com/user/profile') .pipe( catchError(this.handleError) ) .subscribe(user => { this.user = user; }); // POST/PUT/PATCH requests also get the JWT automatically this.http.put('https://api.example.com/user/profile', userData) .subscribe(updatedUser => { this.user = updatedUser; }); // Requests to disallowed routes don't include the JWT this.http.post<{ token: string }>('https://api.example.com/auth/login', credentials) .subscribe(response => { localStorage.setItem('access_token', response.token); }); ``` ### Response #### Success Response (200) - **User**: User profile data. - **{ token: string }**: Authentication token. #### Response Example ```json { "id": "user123", "name": "John Doe", "email": "john.doe@example.com" } ``` #### Error Handling - **401 Unauthorized**: Indicates authentication failure, possibly due to an invalid or expired token. ```typescript private handleError(error: HttpErrorResponse) { if (error.status === 401) { console.error('Authentication failed - token may be invalid or expired'); } return throwError(() => error); } ``` ``` -------------------------------- ### Configure JWT with Custom Options Factory Source: https://github.com/auth0/angular2-jwt/blob/main/EXAMPLES.md Use a custom factory function when the tokenGetter relies on a service or asynchronous storage. Import JWT_OPTIONS and provide your factory function using jwtOptionsProvider. ```typescript import { JwtModule, JWT_OPTIONS } from '@auth0/angular-jwt'; import { TokenService } from './app.tokenservice'; // ... 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] }) ``` -------------------------------- ### Configure Allowed Domains and Disallowed Routes Source: https://context7.com/auth0/angular2-jwt/llms.txt Control which domains receive the JWT and which specific routes should be excluded from JWT authentication. Domains can be strings or RegExp patterns, and disallowed routes require the protocol or '//' for protocol-agnostic matching. ```typescript import { JwtModule } from '@auth0/angular-jwt'; @NgModule({ imports: [ JwtModule.forRoot({ config: { tokenGetter: () => localStorage.getItem('access_token'), // Domains that should receive the JWT (port required for non-standard ports) allowedDomains: [ 'api.example.com', // Standard HTTPS port (443) 'localhost:3001', // Non-standard port required /.*\.example\.com/ // RegExp for subdomains ], // Routes that should NOT receive the JWT disallowedRoutes: [ 'http://api.example.com/auth/login', // Specific protocol 'https://api.example.com/auth/register', '//api.example.com/public/health', // Any protocol /api\.example\.com\/public\/.*/ // RegExp pattern ] } }) ] }) export class AppModule {} ``` -------------------------------- ### Configure JwtModule with Static Auth Scheme Source: https://github.com/auth0/angular2-jwt/blob/main/API.md Set a custom static string to prefix the token for each request, overriding the default 'Bearer '. ```typescript JwtModule.forRoot({ config: { // ... authScheme: "Basic ", }, }); ``` -------------------------------- ### Configure JwtModule to Throw No Token Error Source: https://github.com/auth0/angular2-jwt/blob/main/API.md Enable `throwNoTokenError` to `true` to make the module throw an error when a token cannot be retrieved by the `tokenGetter`. ```typescript JwtModule.forRoot({ config: { // ... throwNoTokenError: true, }, }); ``` -------------------------------- ### Make authenticated HTTP requests Source: https://github.com/auth0/angular2-jwt/blob/main/README.md Inject HttpClient and use it to make requests. The JWT will be automatically attached as an Authorization header. ```typescript 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) ); } } ``` -------------------------------- ### Dynamic Auth Scheme Configuration Source: https://context7.com/auth0/angular2-jwt/llms.txt Use a function for the authScheme option to dynamically set the authentication scheme based on the request URL. ```typescript import { JwtModule } from '@auth0/angular-jwt'; import { HttpRequest } from '@angular/common/http'; @NgModule({ imports: [ JwtModule.forRoot({ config: { tokenGetter: () => localStorage.getItem('access_token'), allowedDomains: ['api.example.com', 'legacy-api.example.com'], authScheme: (request: HttpRequest) => { // Use Basic auth for legacy API if (request.url.includes('legacy-api')) { return 'Basic '; } // Use Bearer for modern API return 'Bearer '; } } }) ] }) export class AppModule {} ``` -------------------------------- ### Configure JwtModule with Allowed Domains Source: https://github.com/auth0/angular2-jwt/blob/main/API.md Specify an array of domains to which authenticated requests should be sent. Ports are only required for non-standard ports. ```typescript JwtModule.forRoot({ config: { // ... allowedDomains: ["localhost:3001", "foo.com", "bar.com"], }, }); ``` -------------------------------- ### JwtHelperService - decodeToken Source: https://github.com/auth0/angular2-jwt/blob/main/API.md The `decodeToken` function decodes the JWT. ```APIDOC ## JwtHelperService - decodeToken ### Description This helper function decodes the JWT. ### Method Service Method ### Endpoint N/A ### Parameters #### Path Parameters - **token** (string) - Required - The JWT to decode. ### Request Example ```typescript import { JwtHelperService } from '@auth0/angular-jwt'; // ... constructor(public jwtHelper: JwtHelperService) {} ngOnInit() { console.log(this.jwtHelper.decodeToken(token)); // token } ``` ### Response #### Success Response (object) - **decodedToken** (object) - The decoded JWT payload. #### Response Example ```json { "sub": "1234567890", "name": "John Doe", "iat": 1516239022 } ``` ``` -------------------------------- ### Configure JwtModule with Conditional Token Getter Source: https://github.com/auth0/angular2-jwt/blob/main/API.md Configure a token getter function that conditionally retrieves tokens based on the request URL, useful for multiple domains. ```typescript JwtModule.forRoot({ config: { // ... tokenGetter: (request) => { if (request.url.includes("foo")) { return localStorage.getItem("access_token_foo"); } return localStorage.getItem("access_token"); }, }, }); ``` -------------------------------- ### tokenGetter with HttpRequest Object Source: https://context7.com/auth0/angular2-jwt/llms.txt Implement a tokenGetter function that accepts the HttpRequest object to dynamically return different tokens based on the request URL. ```typescript import { JwtModule } from '@auth0/angular-jwt'; import { HttpRequest } from '@angular/common/http'; @NgModule({ imports: [ JwtModule.forRoot({ config: { tokenGetter: (request: HttpRequest) => { // Return different tokens for different APIs if (request.url.includes('api.service-a.com')) { return localStorage.getItem('service_a_token'); } if (request.url.includes('api.service-b.com')) { return localStorage.getItem('service_b_token'); } return localStorage.getItem('default_token'); }, allowedDomains: ['api.service-a.com', 'api.service-b.com'] } }) ] }) export class AppModule {} ``` -------------------------------- ### Configure JwtModule with Custom Header Name Source: https://github.com/auth0/angular2-jwt/blob/main/API.md Change the default 'Authorization' header name by providing a custom string value for `headerName`. ```typescript JwtModule.forRoot({ config: { // ... headerName: "Your Header Name", }, }); ``` -------------------------------- ### Custom Options Factory with JWT_OPTIONS Source: https://context7.com/auth0/angular2-jwt/llms.txt Use a custom factory function with the JWT_OPTIONS injection token for advanced scenarios, such as token retrieval depending on a service or asynchronous operations. ```typescript import { NgModule } from '@angular/core'; import { JwtModule, JWT_OPTIONS } from '@auth0/angular-jwt'; import { AuthService } from './auth.service'; export function jwtOptionsFactory(authService: AuthService) { return { tokenGetter: () => authService.getToken(), allowedDomains: ['api.example.com'], disallowedRoutes: ['http://api.example.com/auth/login'] }; } @NgModule({ imports: [ JwtModule.forRoot({ jwtOptionsProvider: { provide: JWT_OPTIONS, useFactory: jwtOptionsFactory, deps: [AuthService] } }) ], providers: [AuthService] }) export class AppModule {} ``` -------------------------------- ### Decode JWT using JwtHelperService Source: https://github.com/auth0/angular2-jwt/blob/main/API.md Decode a JWT using the `decodeToken` method from `JwtHelperService`. This method parses the token and returns its payload as a JavaScript object. Ensure the token is provided as an argument. ```typescript import { JwtHelperService } from '@auth0/angular-jwt'; // ... constructor(public jwtHelper: JwtHelperService) {} ngOnInit() { console.log(this.jwtHelper.decodeToken(token)); // token } ``` -------------------------------- ### Decode JWT Token using JwtHelperService Source: https://context7.com/auth0/angular2-jwt/llms.txt Decode a JWT token using JwtHelperService to retrieve its payload. Supports tokens obtained from the configured tokenGetter or a specific token string. ```typescript import { Component, OnInit } from '@angular/core'; import { JwtHelperService } from '@auth0/angular-jwt'; interface TokenPayload { sub: string; name: string; email: string; roles: string[]; iat: number; exp: number; } @Component({ selector: 'app-profile', template: `
Welcome, {{ userName }}
` }) export class ProfileComponent implements OnInit { userName: string = ''; constructor(private jwtHelper: JwtHelperService) {} ngOnInit() { // Decode token from configured tokenGetter const decoded = this.jwtHelper.decodeToken(); if (decoded) { this.userName = decoded.name; console.log('User ID:', decoded.sub); console.log('Roles:', decoded.roles); } // Or decode a specific token string const specificToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'; const payload = this.jwtHelper.decodeToken(specificToken); // payload = { sub: "1234567890", name: "John Doe", iat: 1516239022 } } } ``` -------------------------------- ### JwtHelperService - getTokenExpirationDate Source: https://github.com/auth0/angular2-jwt/blob/main/API.md The `getTokenExpirationDate` function retrieves the expiration date of the JWT. ```APIDOC ## JwtHelperService - getTokenExpirationDate ### Description This helper function retrieves the expiration date of the JWT. ### Method Service Method ### Endpoint N/A ### Parameters #### Request Body - **token** (string) - Optional - The token to check. If not provided, the default token from the service will be used. ### Request Example ```typescript import { JwtHelperService } from '@auth0/angular-jwt'; // ... constructor(public jwtHelper: JwtHelperService) {} ngOnInit() { console.log(this.jwtHelper.getTokenExpirationDate()); // date } ``` ### Response #### Success Response (Date) - **expirationDate** (Date) - The expiration date of the token. #### Response Example ```json "2023-10-27T10:00:00.000Z" ``` ``` -------------------------------- ### JwtHelperService - isTokenExpired Source: https://github.com/auth0/angular2-jwt/blob/main/API.md The `isTokenExpired` function checks if the JWT is expired. ```APIDOC ## JwtHelperService - isTokenExpired ### Description This helper function checks if the JWT is expired. ### Method Service Method ### Endpoint N/A ### Parameters #### Request Body - **token** (string) - Optional - The token to check. If not provided, the default token from the service will be used. ### Request Example ```typescript import { JwtHelperService } from '@auth0/angular-jwt'; // ... constructor(public jwtHelper: JwtHelperService) {} ngOnInit() { console.log(this.jwtHelper.isTokenExpired()); // true or false } ``` ### Response #### Success Response (boolean) - **isExpired** (boolean) - True if the token is expired, false otherwise. #### Response Example ```json true ``` ``` -------------------------------- ### JwtHelperService.isTokenExpired() Source: https://context7.com/auth0/angular2-jwt/llms.txt Checks if a JWT token has expired. An optional offset in seconds can be provided to determine if the token will expire soon. ```APIDOC ## JwtHelperService.isTokenExpired() ### Description Checks whether a JWT token has expired. Optionally accepts an offset in seconds to check if the token will expire soon. ### Method `isTokenExpired(token?: string, offsetInSeconds?: number): boolean` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Check if the token from the configured tokenGetter is expired const isExpired = this.jwtHelper.isTokenExpired(); // Check if token expires within the next 5 minutes (300 seconds) const expiresWithin5Min = this.jwtHelper.isTokenExpired(undefined, 300); // Check expiration of a specific token const specificToken = 'your_token_here'; const isSpecificTokenExpired = this.jwtHelper.isTokenExpired(specificToken); ``` ### Response #### Success Response (200) - **boolean**: `true` if the token is expired, `false` otherwise. #### Response Example ```json true ``` #### Error Handling - If the token is invalid or cannot be parsed, the behavior is undefined and may result in errors. ``` -------------------------------- ### Configure JwtModule to Skip Expired Tokens Source: https://github.com/auth0/angular2-jwt/blob/main/API.md Set `skipWhenExpired` to true in the JwtModule configuration to prevent sending expired JWTs with HttpClient requests. This is useful for security and to avoid unnecessary network traffic. ```typescript // ... JwtModule.forRoot({ config: { // ... skipWhenExpired: true, }, }); ``` -------------------------------- ### Check if JWT is Expired using JwtHelperService Source: https://github.com/auth0/angular2-jwt/blob/main/API.md Use the `isTokenExpired` method from `JwtHelperService` to determine if the current JWT is expired. Ensure `JwtHelperService` is injected into your component or service. ```typescript import { JwtHelperService } from '@auth0/angular-jwt'; // ... constructor(public jwtHelper: JwtHelperService) {} ngOnInit() { console.log(this.jwtHelper.isTokenExpired()); // true or false } ``` -------------------------------- ### Configure skipWhenExpired Source: https://github.com/auth0/angular2-jwt/blob/main/API.md By default, the user's JWT will be sent in HttpClient requests even if it is expired. You may choose to not allow the token to be sent if it is expired by setting `skipWhenExpired` to true. ```APIDOC ## Configure skipWhenExpired ### Description By default, the user's JWT will be sent in `HttpClient` requests even if it is expired. You may choose to not allow the token to be sent if it is expired by setting `skipWhenExpired` to true. ### Method Configuration ### Endpoint N/A ### Parameters #### Request Body - **skipWhenExpired** (boolean) - Optional - If true, the token will not be sent if it is expired. ### Request Example ```typescript // ... JwtModule.forRoot({ config: { // ... skipWhenExpired: true, }, }); ``` ### Response N/A ``` -------------------------------- ### JwtHelperService.getTokenExpirationDate() Source: https://context7.com/auth0/angular2-jwt/llms.txt Retrieves the expiration date of a JWT token as a JavaScript Date object. Returns null if the token does not contain an expiration claim. ```APIDOC ## JwtHelperService.getTokenExpirationDate() ### Description Returns the expiration date of a JWT token as a JavaScript Date object, or null if the token has no expiration claim. ### Method `getTokenExpirationDate(token?: string): Date | null` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Get expiration date from the configured tokenGetter const expirationDate = this.jwtHelper.getTokenExpirationDate(); // Check expiration of a specific token const token = 'your_token_here'; const expDate = this.jwtHelper.getTokenExpirationDate(token); ``` ### Response #### Success Response (200) - **Date | null**: A JavaScript Date object representing the token's expiration, or null if no expiration claim is present. #### Response Example ```json "2023-10-27T10:00:00.000Z" ``` #### Error Handling - If the token is invalid or cannot be parsed, the behavior is undefined and may result in errors. ``` -------------------------------- ### Angular AuthGuard for Token Validation Source: https://context7.com/auth0/angular2-jwt/llms.txt This guard checks for the presence and validity of a JWT in local storage. It redirects to login if the token is missing or expired. Optionally, it can verify if the user has the required roles specified in route data. ```typescript import { Injectable } from '@angular/core'; import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import { JwtHelperService } from '@auth0/angular-jwt'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { constructor( private jwtHelper: JwtHelperService, private router: Router ) {} canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): boolean { const token = localStorage.getItem('access_token'); // Check if token exists and is not expired if (token && !this.jwtHelper.isTokenExpired(token)) { // Optionally check for required roles const requiredRoles = route.data['roles'] as string[]; if (requiredRoles) { const decoded = this.jwtHelper.decodeToken<{ roles: string[] }>(token); const hasRequiredRole = requiredRoles.some(role => decoded?.roles?.includes(role) ); if (!hasRequiredRole) { this.router.navigate(['/unauthorized']); return false; } } return true; } // Token missing or expired - redirect to login this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } }); return false; } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.