NodeJs – 从JWT令牌检索用户信息?

节点和angular度。 我有一个MEAN堆栈身份validation应用程序,我正在设置成功loginJWT令牌如下,并将其存储在控制器中的会话中。 通过服务拦截器将JWT令牌分配给config.headers:

var token = jwt.sign({id: user._id}, secret.secretToken, { expiresIn: tokenManager.TOKEN_EXPIRATION_SEC }); return res.json({token:token}); 

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; } }; }]); 

现在我想从令牌获取login的用户详细信息,我该怎么做? 我尝试如下,不工作。 当我从Users.js文件logging错误,它说“ReferenceError:标题未定义”

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:

 authServices.factory('UserService',['$http', function($http) { return { me:function() { return $http.get(options.api.base_url + '/me'); } } }]); 

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); } 

我是否也必须将令牌作为parameter passing以检索用户详细信息? 或者将用户的详细信息保存在单独的会话variables中?

首先,使用Passport中间件进行用户授权处理是一个很好的做法。 它需要parsing您的请求的所有肮脏的工作,并提供了许多授权选项。 现在你的Node.js代码。 您需要使用jwt方法validation并parsing传递的令牌,然后通过从令牌中提取的idfind用户:

 exports.me = function(req,res){ if (req.headers && req.headers.authorization) { var authorization = headers.authorization, 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); } 

你正在用两个callback调用函数UserService.me ,尽pipe函数不接受任何参数。 我想你想要做的是:

 $scope.me = function() { UserService.me().then(function(res) { $scope.myDetails = res; }, function() { console.log('Failed to fetch details'); $rootScope.error = 'Failed to fetch details'; }); }; 

另请注意,$ http方法返回一个响应对象 。 确保你想要的不是$scope.myDetails = res.data

而在你的Users.js文件中,你直接使用了variablesheaders.authorization ,而它应该是req.header.authorization

 var authorization = req.headers.authorization;