Search code examples
javascripttypescriptauth-token

Read property from a Json object in typescript/javascript


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?


Solution

  • 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];