1

一直在处理一个艰难的问题,即使在深入研究 Passport 源代码几个小时后我也无法弄清楚。

我正在使用带有 jwt 的 passport.js 设置,并且发生了一件奇怪的事情,因为我在路由上的身份验证(在我的节点服务器上,使用封装路由的 passport.authenticate 进行身份验证)工作得很好 - 但是对 isAuthenticated 的调用失败尽管是登录并调用 jwt 策略并成功返回 done(null,user) 每次。

代码如下:

应用程序.js

let strategy2 = new JwtStrategy(jwtOptions, function(jwt_payload, done) {

  Auth.findById(jwt_payload.id).then(user=>{
  if (user) {

    done(null, user);
  } else {
    done(null, false);
  }
  });

});
// use the strategy
passport.use(strategy2);

auth.controller.js 中的相关代码是:

exports.logged_in = function(req,res){

        res.send(req.isAuthenticated() ? req.user :'0');
    }

exports.auth_post = async (req, res, next) => {
    passport.authenticate(['local','jwt'], {session: false}, (err, user, info) => {
        if (err || !user) {
            return res.status(400).json({
                message: 'Something is not right',
                user   : user
            });
        }
        else{
       req.login(user, {session: false}, (err) => {
           if (err) {
               res.send(err);
           }
           // generate a signed json web token with the contents of user object and return it in the response
           // the only personalized value that goes into our token
            let payload = { id: user.id };
            let token = jwt.sign(payload, 'secret');
            res.json({ msg: 'ok', token: token });
            } 
    );}
    })(req, res);
};

然后深入到 passport.js,调用 isAuthenticated 方法,如下所示:

req.isAuthenticated = function() {
  var property = 'user';
  if (this._passport && this._passport.instance) {

    property = this._passport.instance._userProperty || 'user';

    return (this[property]) ? true : false;
  }

尽管属性为“用户”,但 this[property] 返回 null。

到目前为止,我已经尝试了许多相关的答案,包括弄乱我的 .findOne 函数来获取用户,以及修改我的中间件设置的顺序(这通常与会话有关,我没有与 JWT 一起使用)。

谢谢你的帮助,

4

0 回答 0