Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get user role from jwt token

Tags:

angular

token

jwt

In server side I have those code to login:

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

In client side I need code to check login and isAdmin.

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

isAdmin(){
  //???
}

How can I get user role from token?

like image 994
DzouSi Avatar asked Aug 02 '17 10:08

DzouSi


People also ask

Can JWT contain roles?

JWT settings at the site level will override team-level defaults. Once you've configured your site, go back to your authentication provider and set roles for the users you want to grant access to. For example, you can set specific roles for people in a specific GitHub organization, or with a specific company email.

What is the role of JWT token?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.


1 Answers

Say you had this JWT (example from here)

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

You could 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)
like image 157
0mpurdy Avatar answered Oct 21 '22 21:10

0mpurdy