Decode JWT Token In Angular

In this article, We will explore how to decode JWT token in angular, Here I am using @auth0/angular-jwt library.

Let us first see what JWT Token is

A JWT token is a JSON Object, which contains all the required information about a user. JWT tokens are small in size for transmission and are also secure due to the algorithms (HMAC, RSA) used to create them.

A JWT token consists of three parts: Header, Payload, and Signature.

 Example of JWT Token

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE2MjU4OTU5MTIsImV4cCI6MTY1NzQzMTkxMiwiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSIsIkdpdmVuTmFtZSI6IkpvaG5ueSIsIlN1cm5hbWUiOiJSb2NrZXQiLCJFbWFpbCI6Impyb2NrZXRAZXhhbXBsZS5jb20iLCJSb2xlIjpbIk1hbmFnZXIiLCJQcm9qZWN0IEFkbWluaXN0cmF0b3IiXX0.iWHf3Kwm61w-XqKWxzUHdN2vriWAr_NEBKnCRbZZDg4
  1. The header contains the algorithm and token type of the token.
  2. The Second part Payload contains all details about the user.
  3. Signature use for verifying the identity of the sender and ensure the message was not modified during transmission.

How angular-jwt helps to decode Token

Step 1:- create a new Angular app using the following Command

ng new JwtHelper

Here I have given my app name as JwtHelper.

Step 2:-  Next Step is To install the angular-jwt library from the npm Package using the following command

npm i @auth0/angular-jwt

if get an error then use

npm i @auth0/angular-jwt --force

Note: This Library is not compatible with lower version than Angular 4.3

Step 3:- Next Step is to import Some Dependencies like JwtHelperService so let’s add it in app.module.ts

add the following line in the import

import { JwtHelperService } from '@auth0/angular-jwt';

and this in provider section:-

{ provide: JWT_OPTIONS, useValue: JWT_OPTIONS }, JwtHelperService

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { JwtHelperService, JWT_OPTIONS } from '@auth0/angular-jwt';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
  ],
  providers: [{ provide: JWT_OPTIONS, useValue: JWT_OPTIONS }, JwtHelperService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 4:-Now Lets Add JwtHelperService in the constructor. Add the following line in a constructor in app.component.ts

private jwtHelper :JwtHelperService

Step 5:- Now create a function to DecodeToken

  GetTokenDecoded() {
    console.log(this.jwtHelper.decodeToken(this.expToken))
    this.tokenPayload = JSON.stringify(this.jwtHelper.decodeToken(this.expToken));
  }

Step 6 :- with the help of JwtHelperService you can get the expiration Date and can Check if the token is expired or not with the help of following code

getTokenExpirationDate() {
  this.expirationDate = this.jwtHelper.getTokenExpirationDate(this.expToken);
}
isAuthenticated(): boolean {
  return !this.jwtHelper.isTokenExpired(this.expToken);
}

AppComponent.ts 

import { Component } from '@angular/core';
import { JwtHelperService } from '@auth0/angular-jwt';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],

})
export class AppComponent {
  expToken: any;
  tokenPayload: any;
  expirationDate: any;
  constructor(private jwtHelper: JwtHelperService) {
    this.expToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE2MjU4OTU5MTIsImV4cCI6MTY1NzQzMTkxMiwiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSIsIkdpdmVuTmFtZSI6IkpvaG5ueSIsIlN1cm5hbWUiOiJSb2NrZXQiLCJFbWFpbCI6Impyb2NrZXRAZXhhbXBsZS5jb20iLCJSb2xlIjpbIk1hbmFnZXIiLCJQcm9qZWN0IEFkbWluaXN0cmF0b3IiXX0.iWHf3Kwm61w-XqKWxzUHdN2vriWAr_NEBKnCRbZZDg4';
    this.GetTokenDecoded();
    this.getTokenExpirationDate();
  }

  GetTokenDecoded() {
    console.log(this.jwtHelper.decodeToken(this.expToken))
    this.tokenPayload = JSON.stringify(this.jwtHelper.decodeToken(this.expToken));
  }
  getTokenExpirationDate() {
    this.expirationDate = this.jwtHelper.getTokenExpirationDate(this.expToken);
  }
  isAuthenticated(): boolean {
    return !this.jwtHelper.isTokenExpired(this.expToken);
  }

}

Hope this article helps you guys

1 Comment

  1. Edwin Moreno

    Hi!

    is there a way to verify the token signature by using a public key?

    use case: verify token signature with public key from angular to give access or deny using guard

    Thank you!

    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories