【发布时间】:2021-09-01 23:50:50
【问题描述】:
我需要解码在登录期间由 API 发送的 jwt 令牌。 如何以角度解码 jwt 令牌?
【问题讨论】:
我需要解码在登录期间由 API 发送的 jwt 令牌。 如何以角度解码 jwt 令牌?
【问题讨论】:
我们可以在 Angular 中解码 JWT 令牌,因为您需要在 Angular 应用中安装“@auth0/angular-jwt”npm 模块。 JWT的解码有以下步骤
npm i @auth0/angular-jwt -s
import { JwtModule } from "@auth0/angular-jwt";
在 imports:[] 部分添加此JwtModule.forRoot({
config: {
tokenGetter: () => localStorage.getItem('access_token')
}
})
代码如下所示。
import { JwtHelperService } from '@auth0/angular-jwt';
constructor(private jwtHelper: JwtHelperService) {}
someMethod(){
const token = this.jwtHelper.decodeToken(localStorage.getItem('access_token'));
}
注意: JwtHelperService还有其他方法,根据需要使用。
【讨论】:
我认为解码 JWT 令牌不需要外部模块。可以用JSatob()函数来完成。
这是一个使用 JS 的通用函数 atob() 与 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));
}
这是一个有效的 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 等库