How to get user role from jwt token

On the server side, I have the login code:

return jsonify({'email': email, 'token': create_token(email, isAdmin, password)})

      

On the client side, I need some code to check the login and isAdmin.

isLogged() {
if (localStorage.getItem('currentUser') &&
    JSON.parse(localStorage.getItem('currentUser')).email) {
  return true;
}
return false;
}

isAdmin(){
  //???
}

      

How can I get the user's role from the token?

+3


source to share


1 answer


Say you had this JWT ( example from here )

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

      

You can use something like this to decode it:



let jwt = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ'

let jwtData = jwt.split('.')[1]
let decodedJwtJsonData = window.atob(jwtData)
let decodedJwtData = JSON.parse(decodedJwtJsonData)

let isAdmin = decodedJwtData.admin

console.log('jwtData: ' + jwtData)
console.log('decodedJwtJsonData: ' + decodedJwtJsonData)
console.log('decodedJwtData: ' + decodedJwtData)
console.log('Is admin: ' + isAdmin)
      

Run code


+7


source







All Articles