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

Sri*_*ri7 16 javascript node.js jwt angularjs

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

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

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;
            }               
        };
    }]);
Run Code Online (Sandbox Code Playgroud)

现在我想从令牌中获取登录的用户详细信息,我该怎么做?我尝试如下,不工作.当我从Users.js文件记录错误时,它说"ReferenceError:headers 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';
    })
  };
Run Code Online (Sandbox Code Playgroud)

authService.js:

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

Users.js(Node):

 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);
}
Run Code Online (Sandbox Code Playgroud)

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

Con*_*rev 28

首先,使用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);
}
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢你 !有效。只需要做一个简单的更改,即可解码= jwt.verify(authorization.split('')[1],secret.secretToken); 因为我将Bearer +令牌作为令牌。 (2认同)

小智 6

从请求数据中查找令牌:

const usertoken = req.headers.authorization;
const token = usertoken.split(' ');
const decoded = jwt.verify(token[1], 'secret-key');
console.log(decoded);
Run Code Online (Sandbox Code Playgroud)