node.js - 我想通过分配给用户的 json Web token 获取用户信息

标签 node.js sails.js jwt

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

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

};

最佳答案

您需要verify and parse the passed token使用 jwt 方法,然后通过 id extracted 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?

关于node.js - 我想通过分配给用户的 json Web token 获取用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43149701/

相关文章:

node.js - npm runsequelize 无法解决

javascript - npm install -SE 带有次要版本符号

node.js - 从 sails 服务访问 Controller 方法?

javascript - Cookie 只发送到一个 API

javascript - 如何检查运行 Web 应用程序的设备

node.js - ExpressJS 作为编排层?

node.js - 尝试从 Sails.js 应用程序执行 MongoDB 查询时出现奇怪的 "timeouts"

javascript - sails.js 使用 async.js 查找每个并行调用的查询 - 每个都提前返回

node.js - socketio-jwt 断开过期的 token

authentication - 我们可以在 Asp.NET Core 中销毁/无效 JWT token 吗?