How to decode the JWT encoded token payload on client-side in angular?
Asked Answered
D

6

110

I am getting one JWT encoded access token from my API in response. But I am not able to decode it and get it in JSON format. I tried using the angular2-jwt library for it, but it did not worked. I am writing my code below:

 setXAuthorizationToken(client){
    let requestHeader = new Headers();
    requestHeader.append('Content-Type', 'application/x-www-form-urlencoded');
    this.http.post(client.clientURL + "oauth/token", 'grant_type=password&client_id=toto&client_secret=sec&' +  'username=' + client.username
    + '&password=' + client.password, {
      headers: requestHeader
    }).map(res=>res.json())
    .subscribe((token) =>{
      if(!token.access_token){
          return;
      }
      else{
       var decompressToken = LZString.decompressFromEncodedURIComponent(token.access_token);
       console.log(decompressToken);
}
    });
    }

Can anybody please help me solve this issue?

Disclosure answered 3/1, 2018 at 10:37 Comment(0)
L
141

I use Auth0's jwt-decode package for decoding JWT token in Angular; this package works for me fine.

After installing the package through this command:

npm install jwt-decode

Import this package into your TypeScript class using this syntax:

import * as jwt_decode from "jwt-decode";

Or for newer versions (3 and above):

import jwt_decode from 'jwt-decode';

Then use this library method for decoding your access token like this:

getDecodedAccessToken(token: string): any {
  try {
    return jwt_decode(token);
  } catch(Error) {
    return null;
  }
}

The token parameter defines your access token which comes from your API.

The jwt_decode method returns the decoded token info as an object; you can access any info from your token.

Example

const tokenInfo = this.getDecodedAccessToken(token); // decode token
const expireDate = tokenInfo.exp; // get token expiration dateTime
console.log(tokenInfo); // show decoded token object in console

jwt-decode is a small browser library that helps to decode JWTs token which is Base64Url encoded.

IMPORTANT: This library doesn't validate the token, any well formed JWT can be decoded. You should validate the token in your server-side logic by using something like express-jwt, koa-jwt, Owin Bearer JWT, etc.

Lengthy answered 16/1, 2018 at 19:0 Comment(3)
is there any similar available in react native with expoJohnsen
@Johnsen please check this library react-native-pure-jwt in this link : npmjs.com/package/react-native-pure-jwtLengthy
This throws an error with an azure token. So I used: @auth0/angular-jwtLength
T
122

Try the JavaScript built in function atob(). Like this:

atob(token.split('.')[1])

Notes:

  • The token is actually a string.

  • If you want to know why i split the token you should check this website jwt.io.

Trueman answered 11/8, 2019 at 23:54 Comment(2)
With that, it is even more Genius. Thank you for the idea: JSON.parse(atob(token.split('.')[1]))Gamali
atob() only worked for some of our tokens. Other tokens could not be decoded with this. We had to use the jwt-decode npm library in the end.Cormophyte
B
56

Use @auth0/angular-jwt


Step - 1 : Install using npm

npm install @auth0/angular-jwt


Step - 2 : Import the package

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


Step - 3 : Create an instance and use

const helper = new JwtHelperService();

const decodedToken = helper.decodeToken(myRawToken);

// Other functions
const expirationDate = helper.getTokenExpirationDate(myRawToken);
const isExpired = helper.isTokenExpired(myRawToken);
Bakst answered 27/6, 2018 at 9:5 Comment(3)
do I need to sign up on Auth0 for using this? Is it only limited to 7000 users as it says?Secco
@RameshPareek, github.com/auth0/angular2-jwt/blob/main/projects/angular-jwt/… it's just a library, it doesn't make any calls to any service.Breskin
When injecting this via app.module.ts also add a provider for JWT_OPTIONS. https://mcmap.net/q/196317/-nullinjectorerror-no-provider-for-jwthelperserviceBoru
H
7

atob function does not parse cyrillic or hebrew correctly so I must use JwtHelperService().decodeToken(token) instead.

Henghold answered 4/12, 2019 at 15:15 Comment(0)
M
4

I have defined my JWTService as below! Hope it helps. It is in TypeScript but can be used in vanilla javascript by just copying the code.

import { Injectable } from "@angular/core";

@Injectable()
export class JWTService {
    private chars: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    private atob(input) {
        var str = String(input).replace(/=+$/, '');
        if (str.length % 4 == 1) {
            throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");
        }
        for (
            // initialize result and counters
            var bc = 0, bs, buffer, idx = 0, output = '';
            // get next character
            buffer = str.charAt(idx++);
            // character found in table? initialize bit storage and add its ascii value;
            ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
                // and if not first of each 4 characters,
                // convert the first 8 bits to one ascii character
                bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
        ) {
            // try to find character in table (0-63, not found => -1)
            buffer = this.chars.indexOf(buffer);
        }
        return output;
    };

    parseJwt(token) {
        var base64Url = token.split('.')[1];
        var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        var jsonPayload = decodeURIComponent(this.atob(base64).split('').map(function (c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));

        return JSON.parse(jsonPayload);
    };
}
Malt answered 26/10, 2020 at 11:29 Comment(0)
M
-7

Store your token on login like this:

localStorage.setItem("token")

Then declare a variable like this

decodeToken:any

and decode token by using the following code:

 this.decodedToken = this.jwtHelper.decodeToken(localStorage.setItem("token"));
Mission answered 9/12, 2021 at 7:27 Comment(4)
It will be more clear when you say what the NPM package you used and create an instance for it with the variable jwtHelperOlympe
I think the one I have shared is more understandable then you have shared. without asking NPM package :PMission
Okay, sorry if I misunderstood anything, but can you explain What is the jwtHelper instance you are using?Olympe
Check it here, if you don't know jwtHealper. npmjs.com/package/jwthelperMission

© 2022 - 2024 — McMap. All rights reserved.