Javascript NodeJs - 从 JWT 令牌中检索用户信息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33451298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NodeJs - Retrieve user infor from JWT token?
提问by hakuna
Node and Angular. I have a MEAN stack authentication application where I am setting a JWT token on successful login as follows, and storing it in a session in the controller. Assigning the JWT token to config.headers through service interceptor:
节点和角度。我有一个 MEAN 堆栈身份验证应用程序,我在成功登录时设置 JWT 令牌,如下所示,并将其存储在控制器的会话中。通过服务拦截器将 JWT 令牌分配给 config.headers:
var token = jwt.sign({id: user._id}, secret.secretToken, { expiresIn: tokenManager.TOKEN_EXPIRATION_SEC });
return res.json({token:token});
authservice.js Interceptor(omitted requestError,response and responseError):
authservice.js 拦截器(省略 requestError、response 和 responseError):
authServices.factory('TokenInterceptor', ['$q', '$window', '$location','AuthenticationService',function ($q, $window, $location, AuthenticationService) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
}
return config;
}
};
}]);
Now I wanted to get the logged in user details from the token, How can I do that? I tried as follows, not working. When I log the error from Users.js file it's saying "ReferenceError: headers is not defined"
现在我想从令牌中获取登录的用户详细信息,我该怎么做?我尝试如下,不工作。当我从 Users.js 文件中记录错误时,它说“ReferenceError: headers is not defined”
authController.js:
authController.js:
$scope.me = function() {
UserService.me(function(res) {
$scope.myDetails = res;
}, function() {
console.log('Failed to fetch details');
$rootScope.error = 'Failed to fetch details';
})
};
authService.js:
authService.js:
authServices.factory('UserService',['$http', function($http) {
return {
me:function() {
return $http.get(options.api.base_url + '/me');
}
}
}]);
Users.js (Node):
Users.js(节点):
exports.me = function(req,res){
if (req.headers && req.headers.authorization) {
var authorization =req.headers.authorization;
var part = authorization.split(' ');
//logic here to retrieve the user from database
}
return res.send(200);
}
Do i have to pass the token as a parameter too for retrieving the user details? Or save the user details in a separate session variable as well?
我是否也必须将令牌作为参数传递以检索用户详细信息?还是将用户详细信息也保存在单独的会话变量中?
回答by Constantine Poltyrev
First of all, it is a good practice to use Passport middleware for user authorization handling. It takes all the dirty job of parsing your request and also provides many authorization options. Now for your Node.js code. You need to verify and parse the passed token with jwt methods and then find the user by id extracted from the token:
首先,使用 Passport 中间件进行用户授权处理是一个很好的做法。它承担了解析请求的所有繁琐工作,还提供了许多授权选项。现在是您的 Node.js 代码。您需要使用 jwt 方法验证并解析传递的令牌,然后通过从令牌中提取的 id 找到用户:
exports.me = function(req,res){
if (req.headers && req.headers.authorization) {
var authorization = req.headers.authorization.split(' ')[1],
decoded;
try {
decoded = jwt.verify(authorization, secret.secretToken);
} catch (e) {
return res.status(401).send('unauthorized');
}
var userId = decoded.id;
// Fetch the user by id
User.findOne({_id: userId}).then(function(user){
// Do something with the user
return res.send(200);
});
}
return res.send(500);
}
回答by Ajay yadav
Find a token from request data:
从请求数据中查找令牌:
const usertoken = req.headers.authorization;
const token = usertoken.split(' ');
const decoded = jwt.verify(token[1], 'secret-key');
console.log(decoded);
回答by Pedro M. Silva
Your are calling the function UserService.me
with two callbacks, although the function does not accept any arguments. What I think you want to do is:
您正在UserService.me
使用两个回调调用该函数,尽管该函数不接受任何参数。我认为你想做的是:
$scope.me = function() {
UserService.me().then(function(res) {
$scope.myDetails = res;
}, function() {
console.log('Failed to fetch details');
$rootScope.error = 'Failed to fetch details';
});
};
Also, note that the $http methods return a response object. Make sure that what you want is not a $scope.myDetails = res.data
另外,请注意 $http 方法返回一个响应对象。确保你想要的不是$scope.myDetails = res.data
And in your Users.js file, you are using the variable headers.authorization
directly, whereas it should be req.header.authorization
:
在您的 Users.js 文件中,您headers.authorization
直接使用变量,而它应该是req.header.authorization
:
var authorization = req.headers.authorization;
回答by Anderson Anzileiro
According to the documentation https://github.com/themikenicholson/passport-jwt, you could use request.user
. Note, I'm supposing that you are using passport with passport-jwt.
It's possible because passport during the context of an authentication is setting the request object and populating the user property. So, just access that property. You don't need to do a middleware.
根据文档https://github.com/themikenicholson/passport-jwt,您可以使用request.user
. 请注意,我假设您使用的是带有passport-jwt 的passport。这是可能的,因为在身份验证上下文中的通行证正在设置请求对象并填充用户属性。因此,只需访问该属性。你不需要做中间件。