我从包含Roles的ASP.NET Core API获得JWT令牌。我需要解析每个角色才能获得价值,但一直无法实现价值。有什么想法吗?
我正在尝试为其获取值的属性。我可能不止一个角色:
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
要解析的JWT:
{
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier": "xxx",
"UserId": "cd59f5eb-9477-4b7c-a978-7b1f60f83086",
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role": "Administrator",
"exp": 1543251220,
"iss": "https://localhost:5000",
"aud": "https://localhost:5000"
}
解析如下:
let token = window.localStorage.getItem(ID_TOKEN_KEY)
if (!token || token.split('.').length < 3) {
return false
}
const data = JSON.parse(atob(token.split('.')[1]))
试图获取属性,但由于它是URI而无法获取:
if (data.http://schemas.microsoft.com/ws/2008/06/identity/claims/role === 'Administrator') {
return true
}
答案 0 :(得分:1)
需要像这样访问复杂字符串的属性:
if (data['http://schemas.microsoft.com/ws/2008/06/identity/claims/role'] === 'Administrator') {
return true
}