【问题标题】:How to decode the JWT encoded token payload on client-side in angular?如何在客户端以角度解码 JWT 编码的令牌有效负载?
【发布时间】:2018-06-13 00:40:17
【问题描述】:

作为响应,我从我的 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


    【解决方案1】:

    我使用Auth0's jwt-decode package 在 Angular 中解码 JWT 令牌;这个包很适合我。

    通过此命令安装包后:

    npm install jwt-decode
    

    使用以下语法将此包导入您的 TypeScript 类:

    import * as jwt_decode from "jwt-decode";
    

    或更新版本(3 及以上):

    import jwt_decode from 'jwt-decode';
    

    然后使用这个库方法来解码你的访问令牌,如下所示:

    getDecodedAccessToken(token: string): any {
      try {
        return jwt_decode(token);
      } catch(Error) {
        return null;
      }
    }
    

    token 参数定义您的访问令牌,它来自您的 API。

    jwt_decode 方法将解码后的令牌信息作为对象返回;您可以从您的令牌中访问任何信息。

    示例

    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 是一个小型浏览器库,可帮助解码 Base64Url 编码的 JWTs 令牌。

    重要提示:此库不验证令牌,任何格式正确的 JWT 都可以被解码。您应该在您的 使用 express-jwt、koa-jwt、Owin 之类的服务器端逻辑 承载JWT等

    【讨论】:

    【解决方案2】:

    尝试使用 JavaScript 内置函数 atob()。有点像这样:

    atob(token.split('.')[1])
    

    注意事项:

    • 令牌实际上是一个字符串。

    • 如果你想知道我为什么拆分令牌,你应该查看这个网站jwt.io

    【讨论】:

      【解决方案3】:

      使用@auth0/angular-jwt


      步骤 - 1:使用 npm 安装

      npm install @auth0/angular-jwt
      


      Step - 2 : 导入包

      import { JwtHelperService } from '@auth0/angular-jwt';
      


      Step - 3 : 创建一个实例并使用

      const helper = new JwtHelperService();
      
      const decodedToken = helper.decodeToken(myRawToken);
      
      // Other functions
      const expirationDate = helper.getTokenExpirationDate(myRawToken);
      const isExpired = helper.isTokenExpired(myRawToken);
      

      【讨论】:

      • 我需要注册 Auth0 才能使用它吗?是不是像它说的那样仅限于 7000 个用户?
      【解决方案4】:

      atob 函数无法正确解析西里尔文或希伯来文,因此我必须改用 JwtHelperService().decodeToken(token)

      【讨论】:

        【解决方案5】:

        我已将我的 JWTService 定义如下!希望能帮助到你。它在 TypeScript 中,但可以通过复制代码在 vanilla javascript 中使用。

        import { Injectable } from "@angular/core";
        
        @Injectable()
        export class JWTService {
            private chars: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
            private atob(input) {
                var str = String(input).replace(/=+$/, '');
                if (str.length % 4 == 1) {
                    throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");
                }
                for (
                    // initialize result and counters
                    var bc = 0, bs, buffer, idx = 0, output = '';
                    // get next character
                    buffer = str.charAt(idx++);
                    // character found in table? initialize bit storage and add its ascii value;
                    ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
                        // and if not first of each 4 characters,
                        // convert the first 8 bits to one ascii character
                        bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
                ) {
                    // try to find character in table (0-63, not found => -1)
                    buffer = this.chars.indexOf(buffer);
                }
                return output;
            };
        
            parseJwt(token) {
                var base64Url = token.split('.')[1];
                var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
                var jsonPayload = decodeURIComponent(this.atob(base64).split('').map(function (c) {
                    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
                }).join(''));
        
                return JSON.parse(jsonPayload);
            };
        }
        

        【讨论】:

          【解决方案6】:

          在登录时存储您的令牌,如下所示:

          localStorage.setItem("token")
          

          然后像这样声明一个变量

          decodeToken:任意

          并使用以下代码解码令牌:

           this.decodedToken = this.jwtHelper.decodeToken(localStorage.setItem("token"));
          

          【讨论】:

            猜你喜欢
            • 2017-01-06
            • 2020-02-08
            • 2021-09-01
            • 2018-08-06
            • 2019-06-19
            • 2016-05-29
            • 2015-09-17
            • 2019-10-29
            • 2018-05-18
            相关资源
            最近更新 更多