1

I am working with an auth token with I receive from a third-party API. I have given a sample of the decoded token below,

{
    "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"]
}

I am struggling to read the "name" claim in javascript. How can I read that property in javascript or typescript?

Joshua
  • 2,275
  • 7
  • 41
  • 57

3 Answers3

2

You can access complex property names like this:

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

You could also abstract this away for reusability (like the ClaimTypes in C#)

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

const name = token[ClaimTypes.name];
Phillip
  • 6,033
  • 3
  • 24
  • 34
2

You will get your data in form of a string, convert it to 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

And then read it like parsedJSON["your key"]. Things on the left sides are property names or keys. You can retrive them by

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))
weegee
  • 3,256
  • 2
  • 18
  • 32
0

JSON.parse(yourData) - convert JSON to JS JSON.stringify(yourData) - from JS to JSON

so after JSON.parse you will get JS object and able to get yourData.name

Here you can read: MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

you can try for example: https://jsonformatter.org/json-parser