【问题标题】:Decode jwt token in angular?以角度解码jwt令牌?
【发布时间】:2021-09-01 23:50:50
【问题描述】:

我需要解码在登录期间由 API 发送的 jwt 令牌。 如何以角度解码 jwt 令牌

【问题讨论】:

    标签: angular jwt


    【解决方案1】:

    我们可以在 Angular 中解码 JWT 令牌,因为您需要在 Angular 应用中安装“@auth0/angular-jwt”npm 模块。 JWT的解码有以下步骤

    1. 安装“@auth0/angular-jwt”模块
      npm i @auth0/angular-jwt -s
    2. JwtModule 模块注册到您的 app.module.ts import { JwtModule } from "@auth0/angular-jwt"; imports:[] 部分添加此
    JwtModule.forRoot({
          config: {
            tokenGetter:  () => localStorage.getItem('access_token')
          }
        })
    
    1. 在您的组件中使用“JwtHelperService”,或者在您使用时使用它。

    代码如下所示。

    import { JwtHelperService } from '@auth0/angular-jwt';
     constructor(private jwtHelper: JwtHelperService) {}
     someMethod(){
       const token = this.jwtHelper.decodeToken(localStorage.getItem('access_token'));
     }
    

    注意: JwtHelperService还有其他方法,根据需要使用。

    【讨论】:

      【解决方案2】:

      我认为解码 JWT 令牌不需要外部模块。可以用JSatob()函数来完成。

      这是一个使用 JS 的通用函数 atob()Array#splitArray#mapArray#reduce

      function decodeToken(token) {
        const _decodeToken = (token) => {
          try {
            return JSON.parse(atob(token));
          } catch {
            return;
          }
        };
        return token
          .split('.')
          .map(token => _decodeToken(token))
          .reduce((acc, curr) => {
            if (!!curr) acc = { ...acc, ...curr };
            return acc;
          }, Object.create(null));
      }
      

      这是一个有效的 sn-p

      function decodeToken(token) {
        const _decodeToken = (token) => {
          try {
            return JSON.parse(atob(token));
          } catch {
            return;
          }
        };
        return token
          .split('.')
          .map(token => _decodeToken(token))
          .reduce((acc, curr) => {
            if (!!curr) acc = { ...acc, ...curr };
            return acc;
          }, Object.create(null));
      }
      
      const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
      
      console.log(decodeToken(token));

      工作示例:Stackblitz

      【讨论】:

      • 没错,如果你只需要对令牌进行解码,那么上面的例子就足够了。如果您还需要验证令牌,那么最好使用 @auth0/angular-jwt@curity/jwt-validation 等库
      猜你喜欢
      • 2021-12-30
      • 2018-10-05
      • 2018-04-11
      • 2019-05-19
      • 2018-06-13
      • 2018-08-14
      • 2020-05-23
      • 2016-11-15
      • 2021-06-30
      相关资源
      最近更新 更多