如何以角度对客户端上的JWT编码令牌有效载荷进行解码? [英] How to decode the JWT encoded token payload on client-side in angular?
问题描述
作为回应,我从我的API中获得了一个JWT编码的访问令牌.但是我无法对其进行解码并以JSON格式获取它.我尝试为其使用angular2-jwt库,但是没有用.我在下面编写代码:
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?
推荐答案
我使用 jwt-decode
包对角度5中的JWT令牌进行解码;这个包裹对我来说很好.
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
通过以下语法将此包导入您的TypeScript类:
import this package into your TypeScript class through this syntax:
import * as jwt_decode from "jwt-decode";
对于较新版本(3及更高版本):
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;
}
}
令牌
参数定义从API获取的访问令牌
token
parameter define your access token which gets from your API
jwt_decode
方法将解码的令牌信息作为对象返回;您可以访问令牌中的任何信息.
jwt_decode
method return decoded token info as an object; you can access any info into your token.
示例:
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 是一个小型浏览器库,可帮助解码通过Base64Url编码的JWT令牌.
jwt-decode is a small browser library that helps to decode JWTs token which is Base64Url encoded.
重要提示::该库不会验证令牌,任何格式正确的JWT都可以解码.您应该验证自己的令牌通过使用express-jwt,koa-jwt,Owin之类的服务器端逻辑承载JWT等.
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.
这篇关于如何以角度对客户端上的JWT编码令牌有效载荷进行解码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!