'@auth0/angular-jwt : Get claims from decoded token

?I get in my Angular 10 application JWT token by "@auth0/angular-jwt". And after decoding function I get a list of claims like this:

{
  http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: "johndoe", 
  http://schemas.microsoft.com/ws/2008/06/identity/claims/role: "Manager", 
  exp: 1525510870, 
  iss: "http://localhost:5000", 
  aud: "http://localhost:5000"
}

How I can get custom claims by typescript like:

{
  name: "johndoe", 
  role: "Manager", 
}

? Thanks.



Solution 1:[1]

A JWT if made out of 3 parts, you have to decode the one from the middle, that is the body containing the claims, the first one is a header, and the last one - JWT Signature.

So, having a token we want to get it's claims, so we decode the part from the middle and parse it to json so we will be able to access claims as fields of that object.

let token = localStorage.getItem('token');
let decodedJWT = JSON.parse(window.atob(token.split('.')[1]));

console.log('name: ' + decodedJWT.name);
console.log('role: ' + decodedJWT.role);

Solution 2:[2]

I find a solution:

const token = {
  'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name': "johndoe", 
  'http://schemas.microsoft.com/ws/2008/06/identity/claims/role': "Manager", 
  'exp': 1525510870, 
  'iss': "http://localhost:5000", 
  'aud': "http://localhost:5000"
}

const decodedName = token['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name']
const decodedRole = token['http://schemas.microsoft.com/ws/2008/06/identity/claims/role']
console.log(decodedName)
console.log(decodedRole)

Solution 3:[3]

Assuming that your object looks like this:

resultObj = {
  name: "", 
  role: "", 
}

and one of your SO tags are Auth0, you can do this:

try {
  const token = JSON.parse(localStorage.getItem('access-token')!)["AccessToken"];
  const decode = this.jwtHelperService.decodeToken(token);
  let str;
  const newObj = {} as any;
  for (let prop in decode) {
    const val = decode[prop];
    if (prop.includes('/')) {
      str = prop.substring(prop.lastIndexOf('/') + 1, prop.length);
    }
    else {
      str = prop;
    }
    newObj[str] = val;
  }
  this.resultObj = newObj;
} catch (error) {
  console.log(error);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dorin Baba
Solution 2 user2080075
Solution 3 Jnr