如何将凭据传递给 passport.authenticate?

How to Pass Credentials to passport.authenticate?

我正在尝试在使用护照的 node.js Express 应用程序上保护 API 端点。

这是我的路线:

router.post('/api/devices', authController.isAuthorized, catchErrors(deviceController.getDevicesAPI));

这是我的授权方式:

exports.isAuthorized = (req, res, next) => {
  passport.authenticate('local', {session: false}, (err, user, info) => {
    if (err || !user) {
      return res.json({ message: 'Something is not right ', err, info });
    }
    req.login(user, {session: false}, (err) => {
      if (err) {
          res.send(err);
      }
      next();
    });
  })(req, res);
};

从 Postman 或单独的本地服务器,我得到响应:

{
    "message": "Something is not right ",
    "err": null,
    "info": {
        "message": "Missing credentials"
    }
}

这是邮递员配置:

我错过了什么?

您的本地策略是如何配置的?好像是数据库查询问题

作为http://www.passportjs.org/docs/username-password/中的示例,请看我下面的评论

var passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
  function(username, password, done) { //<--- Here is where you pass the UN&PASS
    User.findOne({ username: username }, function(err, user) { //<--- Here is the sample code that should find you a user
      if (err) { return done(err); } //<--- Here could be where the response is coming from
      if (!user) {
        return done(null, false, { message: 'Incorrect username.' });
      }
      if (!user.validPassword(password)) {
        return done(null, false, { message: 'Incorrect password.' });
      }

      return done(null, user); //<--- Here is the sample code that should let you return that user
    });
  }
));

终于从here中挖出来了。 User.authenticate() 是我一直在寻找的方法。

exports.isAuthorized =  async (req, res, next) => {
  const username = req.body.username;
  const password = req.body.password;
  const user = await User.findOne({ email: username });

  if (!user) {
    res.sendStatus(403);
    return;
  }

  user.authenticate(password, function(err, result) {
    if (result) {
      next();
      return;
    }
    res.sendStatus(403);
  });
};