我想获得分配给用户的JSON Web令牌的用户信息

我试图创build一个只允许pipe理员查看页面的策略。 我已经在下面显示了这个策略,但是它并没有返回正确的用户。

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

您需要使用jwt方法verify and parse the passed token ,然后通过extracted from the token的idfind用户:

 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 – 从JWT令牌检索用户信息?