以角度解码 jwt 令牌?

Aja*_*jay 5 jwt angular

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

Aja*_*jay 6

我们可以解码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"; :[]部分添加此内容
JwtModule.forRoot({
      config: {
        tokenGetter:  () => localStorage.getItem('access_token')
      }
    })
Run Code Online (Sandbox Code Playgroud)
  1. 在您的组件中或您需要使用的任何地方使用“JwtHelperService”。

代码如下所示。

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

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


Mic*_*l D 5

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

atob()这是使用 JS和Array#split,Array#map的通用函数Array#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));
}
Run Code Online (Sandbox Code Playgroud)

这是一个工作片段

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));
Run Code Online (Sandbox Code Playgroud)

工作示例:Stackblitz

  • 确切地说,如果您只需要解码令牌,那么上面的示例就足够了。如果您还需要验证令牌,那么最好使用“@auth0/angular-jwt”或“@curity/jwt-validation”等库 (3认同)