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.