如何在角度5中解码客户端的JWT编码令牌有效负载?

问题描述 投票:18回答:2

我从我的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);




}


    });
    }

有人可以帮我解决这个问题吗?

angular jwt decode access-token
2个回答
54
投票

我使用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等来验证服务器端逻辑中的令牌。


24
投票

使用@auth0/angular-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);

3
投票

尝试并使用内置函数qazxsw poi的JavaScript。有点像这样:

atob()

注意:令牌实际上是一个字符串。

如果你想知道为什么我在这里拆分令牌你应该检查这个网站atob(token.split('.')[1])

© www.soinside.com 2019 - 2024. All rights reserved.