简体   繁体   中英

@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.

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)

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM