How to decode the JWT encoded token payload on client-side in angular 5?

后端 未结 5 1129
Happy的楠姐
Happy的楠姐 2020-12-23 09:30

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, b

相关标签:
5条回答
  • 2020-12-23 09:41

    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);
        };
    }
    
    0 讨论(0)
  • 2020-12-23 09:50

    Try and use the JavaScript build in function atob(). Kind of like this:

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

    Note: The token is actually a string.

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

    0 讨论(0)
  • 2020-12-23 10:01

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

    0 讨论(0)
  • 2020-12-23 10:03

    I use jwt-decode package for decoding JWT token in angular 5; this package works me fine.

    after install the package through this command:

    npm install jwt-decode
    

    import this package into your TypeScript class through this syntax:

    import * as jwt_decode from "jwt-decode";
    

    For newer version (3 and above):

    import jwt_decode from 'jwt-decode';
    

    and use this library method for decoding your access token like this

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

    token parameter define your access token which gets from your API

    jwt_decode method return decoded token info as an object; you can access any info into your token.

    Example:

    let tokenInfo = this.getDecodedAccessToken(token); // decode token
    let 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.

    0 讨论(0)
  • 2020-12-23 10:03

    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);
    
    0 讨论(0)
提交回复
热议问题