NodeJs - 从JWT令牌中获取用户信息?
NodeJs - 从JWT令牌中获取用户信息?
Node和Angular。我有一个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拦截器(省略了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; } }; }]);
现在我想从令牌中获取已登录用户的详细信息,我该如何做?我尝试了以下方法,但不起作用。当我从Users.js文件中记录错误时,它显示“ReferenceError: headers is not defined”
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(Node):
exports.me = function(req,res){ if (req.headers && req.headers.authorization) { var authorization =req.headers.authorization; var part = authorization.split(' '); //从数据库中检索用户的逻辑在这里 } return res.send(200); }
我需要将令牌作为参数传递以检索用户详细信息吗?还是也需要将用户详细信息保存在单独的会话变量中?