【问题标题】:I want to get user information with the json web token assigned to the user [duplicate]我想使用分配给用户的 json Web 令牌获取用户信息 [重复]
【发布时间】:2017-08-26 06:11:23
【问题描述】:

我正在尝试创建一个仅允许管理员查看页面的策略。我已经展示了下面的政策,但它没有返回正确的用户。

module.exports = function (req, res, next) {

  User.findOne({ id: token.id }, function (err, user) {
    console.log(user);
    if (err) throw (err);
    if (user.permission === "admin") {
      return next();

    }

    return res.send("You Must be an ADMIN to perform this task");
  });

};

【问题讨论】:

    标签: node.js sails.js jwt


    【解决方案1】:

    你需要用jwt方法verify and parse the passed token然后通过idextracted from the token找到用户:

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

    来源:NodeJs - Retrieve user infor from JWT token?

    【讨论】:

    • 谢谢罗伯特
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 2018-08-12
    • 1970-01-01
    • 2021-03-27
    • 2020-08-21
    • 2021-12-23
    相关资源
    最近更新 更多