我从我的API获得一个JWT编码的访问令牌作为响应。但我无法解码它并以JSON格式获取它。我尝试使用angular2-jwt库,但它没有用。我正在编写下面的代码:
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);
}
});
}
有人可以帮我解决这个问题吗?
我使用jwt-decode
包来解码角度为5的JWT令牌;这个包对我很好。
通过此命令安装包之后:
npm install jwt-decode
通过以下语法将此包导入到TypeScript类中:
import * as jwt_decode from "jwt-decode";
并使用此库方法解码您的访问令牌
getDecodedAccessToken(token: string): any {
try{
return jwt_decode(token);
}
catch(Error){
return null;
}
}
token
参数定义从API获取的访问令牌
jwt_decode
方法将解码后的令牌信息作为对象返回;您可以访问令牌中的任何信息。
例:
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都可以解码。您应该使用express-jwt,koa-jwt,Owin Bearer JWT等来验证服务器端逻辑中的令牌。
步骤1:使用npm安装
npm install @auth0/angular-jwt
步骤2:导入包
import { JwtHelperService } from '@auth0/angular-jwt';
步骤3:创建实例并使用
const helper = new JwtHelperService();
const decodedToken = helper.decodeToken(myRawToken);
// Other functions
const expirationDate = helper.getTokenExpirationDate(myRawToken);
const isExpired = helper.isTokenExpired(myRawToken);
尝试并使用内置函数qazxsw poi的JavaScript。有点像这样:
atob()
注意:令牌实际上是一个字符串。
如果你想知道为什么我在这里拆分令牌你应该检查这个网站atob(token.split('.')[1])
。