简体   繁体   中英

Extract 'Roles' from a JWT in Javascript

I have created a token and sent it to my client application (ReactJS).

{
  UserId: "1",
  http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: "Unset",
  http://schemas.microsoft.com/ws/2008/06/identity/claims/role: Array(2), 
  exp: 1531116565,
  iss: "http://www.example.com", 
…}

The role item looks like this:

[ {0: "User"}, {1, "Admin"} ]

I'm not sure why my roles item is named as a URL. But what I am trying to do is work out if the JWT indicates the user has an Admin role.

How can I check the array of roles, for 'Admin'?

you can try this

const roles = [
  {0: "User"}, {1: "Admin"}
];
let isAdmin = false;
roles.map( role => {
  let r = Object.values( role )
  if ( r[0] == 'Admin' ) {
    isAdmin = true
  }
})

console.log( isAdmin );

Maybe something like this:

const token = localStorage.getItem("x-access-token");

const role = JSON.parse(window.atob(token.split(".")[1])).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