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

节点和角度。我有一个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(省略了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:未定义标头”

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

}

为了检索用户详细信息,我是否也必须将令牌作为参数传递?还是将用户详细信息保存在单独的会话变量中?

回答:

首先,将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);

}

以上是 NodeJs-从JWT令牌中检索用户信息? 的全部内容, 来源链接: utcz.com/qa/406746.html

回到顶部