在服务器端,我有登录的代码:
return jsonify({'email': email, 'token': create_token(email, isAdmin, password)})
在客户端,我需要代码来检查登录和isAdmin。
isLogged() {
if (localStorage.getItem('currentUser') &&
JSON.parse(localStorage.getItem('currentUser')).email) {
return true;
}
return false;
}
isAdmin(){
//???
}
如何从令牌获取用户角色?
答案 0 :(得分:17)
说你有这个JWT(example from here)
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
您可以使用something like this对其进行解码:
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)