angular jwt in typescript

You can use the angular2-jwt package to handle JSON Web Tokens (JWT) in Angular applications. Here are the steps to use JWT in your Angular application using Typescript:

  1. Install angular2-jwt package using npm:
npm install angular2-jwt
25 chars
2 lines
  1. Import the JwtModule in your AppModule:
index.ts
import { JwtModule } from '@auth0/angular-jwt';

@NgModule({
  imports: [
    JwtModule.forRoot({
      config: {
        tokenGetter: () => {
          // return the token from storage or any other source
        },
        allowedDomains: ['localhost:3000', 'example.com'],
        disallowedRoutes: [],
      },
    }),
  ],
  // other module configurations...
})
export class AppModule {}
393 chars
18 lines
  1. Add a tokenGetter function to retrieve the token from your storage, for example, localStorage:
index.ts
export function tokenGetter() {
  return localStorage.getItem('access_token');
}
81 chars
4 lines
  1. Use the JwtHelperService to decode and verify the JWT:
index.ts
import { JwtHelperService } from '@auth0/angular-jwt';

const helper = new JwtHelperService();

const token = localStorage.getItem('access_token');
const decodedToken = helper.decodeToken(token);
const expirationDate = helper.getTokenExpirationDate(token);
const isExpired = helper.isTokenExpired(token);
305 chars
9 lines
  1. You can also use the jwtInterceptor to add the token in the header of HTTP requests:
index.ts
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { JwtInterceptor } from '@auth0/angular-jwt';

@NgModule({
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
    // other providers...
  ],
  // other module configurations...
})
export class AppModule {}
310 chars
12 lines

Now, all your HTTP requests will have the JWT token in the Authorization header.

related categories

gistlibby LogSnag