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?
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.