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?
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With