12

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?

DzouSi
  • 361
  • 3
  • 7
  • 21

1 Answers1

27

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)
0mpurdy
  • 3,198
  • 1
  • 19
  • 28
  • 3
    This solution definitely works, as I just tested it myself. Never the less, I feel no confidence using *window.atob(...)* as it seems so... not Angular'ish. It resembles a bit the old kind of programming with JS. It might simply be just me being ignorant, though. Is there a more TypeScript'ish syntax for that operation? Especially if it's packaged in JWT related library. After all - all the JWT tokens will contain of the three parts where we only want to see the decoded version of the middle one, right? – DonkeyBanana May 12 '18 at 15:12
  • 2
    I think the use of atob is fine. Someone can re-implement atob in typescript and put it up as an npm package but I can't think what problem that would solve. The only issue you could run into is that browsers could implement atob differently but I think if they can't encode/decode base64 you probably have bigger issues with that browser. – Lewis Cianci Mar 03 '20 at 02:20