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

最后都变了- 提交于 2019-12-18 11:01:07

问题


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?


回答1:


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

after install 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";

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 get 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 decoding JWTs token which are 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.




回答2:


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);



回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/48075688/how-to-decode-the-jwt-encoded-token-payload-on-client-side-in-angular-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!