如何使用this.jwtHelper.decodeToken(sessionStorage.getItem(' encodedToken'))解析作为解码的jwt令牌的下面的对象,并且需要从角色获取应用程序(QWE)的特权
name:"ram8"
roles:"{"userid":"991635","privileges":{"QWE":["QQT","RR","RRR","FCC","WWW","WRD","DML","UDE","SDE"]}}"
sub:"123456"
user.tenant.name:"DefaultDomain"
__proto__:Object
现在,使用以下代码获取角色
public getUserRoles(){
let userInfoJSON = JSON.parse(JSON.stringify(this.jwtHelper.decodeToken(sessionStorage.getItem('encodedToken'))));
for (let prop in userInfoJSON) {
if(prop === 'roles'){
let roles = JSON.parse(userInfoJSON[prop]);
for(let rProp in roles){
if(rProp === 'privileges'){
let privileges = JSON.parse(JSON.stringify(roles[rProp]));
for(let prev in privileges){
console.log("prev "+prev+" "+privileges[prev])
this.userRoles = privileges[prev];
}
}
}
break;
}
}
console.log("AuthServiceuserRoles "+this.userRoles);
}
答案 0 :(得分:1)
JSON.parse
解析整个令牌,也解析嵌套对象。
您不需要for循环,只需使用let roles = userInfoJSON.roles
和let privileges = roles.privileges
等
这是我用来查看用户是否具有特定角色的一些示例代码:
let token = localStorage.getItem(jwtTokenName);
if (token && tokenNotExpired(null, token)) {
let tokenDecoded = jwtHelper.decodeToken(token);
if (tokenDecoded.roles && tokenDecoded.roles.length > 0) {
for (let i = 0; i < tokenDecoded.roles.length; i++) {
const role = tokenDecoded.roles[i];
if (roles.indexOf(role) >= 0) {
return true;
}
}
}
}