0

我正在使用从第三方 API 收到的身份验证令牌。我在下面给出了一个解码令牌的样本,

{
    "nbf": 1564128888,
    "exp": 1564132488,
    "iss": "http://example.com:5002",
    "aud": "http://example.com:5002/resources",

    "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": "Micky@gmail.com",
    "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "Micky Mouse",    
    "amr": ["custom"]
}

我正在努力阅读 javascript 中的“名称”声明。如何在 javascript 或 typescript 中读取该属性?

4

3 回答 3

2

您可以像这样访问复杂的属性名称:

const name = token["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"]

您还可以将其抽象为可重用性(ClaimTypesC# 中的)

const ClaimTypes = {
  name: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
  // other relevant claims
};

const name = token[ClaimTypes.name];
于 2019-07-28T15:42:53.260 回答
1

您将以字符串的形式获取数据,将其转换为 json

let jsonData = '{"nbf": 1564128888,"exp": 1564132488,"iss": "http://example.com:5002","aud": "http://example.com:5002/resources","http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": "Micky@gmail.com","http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "Micky Mouse","amr": ["custom"]}'
let parsedJSON = JSON.parse(jsonData)
console.log(parsedJSON["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"]) // Micky Mouse
console.log(parsedJSON["nbf"]) // 1564128888
console.log(parsedJSON["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"]) // Micky@gmail.com

然后像阅读它parsedJSON["your key"]。左侧的东西是属性名称或键。您可以通过以下方式检索它们

let jsonData = '{"nbf": 1564128888,"exp": 1564132488,"iss": "http://example.com:5002","aud": "http://example.com:5002/resources","http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": "Micky@gmail.com","http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "Micky Mouse","amr": ["custom"]}'
let parsedJSON = JSON.parse(jsonData)
console.log(Object.keys(parsedJSON))

于 2019-07-28T16:04:05.993 回答
0

JSON.parse(yourData) - 将 JSON 转换为 JS JSON.stringify(yourData) - 从 JS 转换为 JSON

所以在 JSON.parse 之后你会得到 JS 对象并且能够得到 yourData.name

在这里您可以阅读:MDN: https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

您可以尝试例如:https ://jsonformatter.org/json-parser

于 2019-07-28T15:49:35.127 回答