Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode jwt token in angular?

Tags:

angular

jwt

I've got a requirement to decode jwt token which sent by API during login time. How to decode jwt token in angular?

like image 202
Ajay Avatar asked Sep 01 '26 20:09

Ajay


2 Answers

I don't think an external module is necessary to decode a JWT token. It could be done with JS atob() function.

Here is a general function using JS atob() with Array#split, Array#map and Array#reduce

function decodeToken(token) {
  const _decodeToken = (token) => {
    try {
      return JSON.parse(atob(token));
    } catch {
      return;
    }
  };
  return token
    .split('.')
    .map(token => _decodeToken(token))
    .reduce((acc, curr) => {
      if (!!curr) acc = { ...acc, ...curr };
      return acc;
    }, Object.create(null));
}

Here is a working snippet

function decodeToken(token) {
  const _decodeToken = (token) => {
    try {
      return JSON.parse(atob(token));
    } catch {
      return;
    }
  };
  return token
    .split('.')
    .map(token => _decodeToken(token))
    .reduce((acc, curr) => {
      if (!!curr) acc = { ...acc, ...curr };
      return acc;
    }, Object.create(null));
}

const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';

console.log(decodeToken(token));

Working example: Stackblitz

like image 151
ruth Avatar answered Sep 05 '26 14:09

ruth


We can decode JWT token in angular for that you need to have "@auth0/angular-jwt" npm module installed in your angular app. The decode of JWT has following steps

  1. install "@auth0/angular-jwt" module
    npm i @auth0/angular-jwt -s
  2. Register JwtModule module into your app.module.ts import { JwtModule } from "@auth0/angular-jwt"; under imports:[] section add this
JwtModule.forRoot({
      config: {
        tokenGetter:  () => localStorage.getItem('access_token')
      }
    })
  1. use "JwtHelperService" in your component or wher ever its required for your use.

Code would look like below.

import { JwtHelperService } from '@auth0/angular-jwt';
 constructor(private jwtHelper: JwtHelperService) {}
 someMethod(){
   const token = this.jwtHelper.decodeToken(localStorage.getItem('access_token'));
 }

NOTE: JwtHelperService has other methods too, use according to your need.

like image 20
Ajay Avatar answered Sep 05 '26 12:09

Ajay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!