【问题标题】:Passport authenticate is stuck and does not return any valuePassport authenticate 卡住了,不返回任何值
【发布时间】:2018-11-13 03:17:21
【问题描述】:

此验证工作正常

app.post('/login', passport.authenticate('local-login', {
    successRedirect: '/home',
    failureRedirect: '/login',
    failureFlash: true
  })
);

但我正在尝试在使用 express-validator 进行身份验证之前验证表单的字段。

我带着那个

app.post('/login', function(req, res){
  req.checkBody('email', 'Email is required').notEmpty();
  req.checkBody('email', 'Email is not valid').isEmail();
  req.checkBody('password', 'Password is required').notEmpty();
  var validationErr = req.validationErrors();

  if (validationErr){
    res.render('login', {
      errors: validationErr,
      failureFlash: true
    });
  } else {
    // authenticate once fields have been validated
    passport.authenticate('local-login', {
        successRedirect: '/home',
        failureRedirect: '/login',
        failureFlash: true // allow flash messages
    })
  }
});

使用第二个代码,当我提交表单并且客户端在一段时间后给出错误消息localhost没有发送任何数据时没有任何反应。第一部分工作正常,当我提交一个空表单并达到身份验证方法时,我可以看到所有错误。我怀疑这个question 可能会部分回答我的问题或有点相关,但我无法理解。

passport.js documentation 提供了一个带有函数的示例,但是只有在身份验证成功时才会调用该函数,所以之后。我想在身份验证之前执行字段验证。

如果您需要 passport.authenticate 代码,请告诉我。

【问题讨论】:

    标签: javascript node.js express express-validator


    【解决方案1】:

    passport.authenticate 是一个函数。在您的第一个(工作)代码中,您将其称为中间件,在其中将 (req, res, next) 的对象作为参数传递。

    使用您的第二个代码,您尝试直接调用它并且不带参数,并且客户端超时,因为它没有得到响应。

    如果我没有遗漏什么,您可以通过将 (req, res) 传递给它来完成这项工作,如下所示:

      if (validationErr){
          res.render('login', {
              errors: validationErr,
              failureFlash: true
          });
      } else {
          // authenticate once fields have been validated
          passport.authenticate('local-login', {
              successRedirect: '/home',
              failureRedirect: '/login',
              failureFlash: true // allow flash messages
          })(req, res, next);
      }
    

    【讨论】:

    • 正如 Jim 的回答中所指出的,这里的关键是最终的 (req,req,next),因为 passport.authenticate 是一个中间件,您需要调用 req,res,next) 并传回 res对于函数
    【解决方案2】:

    在尝试引入 express-validator 时,我遇到了完全相同的代码和问题。

    我可以确认添加额外的“(req, res, next);”到 passport.authenticate 函数的末尾确实允许完成身份验证过程和 /login 来处理。

    但是,在护照单独使用此方法进行身份验证后,似乎没有其他用户添加到数据库中。我认为需要对护照进行自定义回调,例如:

    http://www.passportjs.org/docs/authenticate/

    使用示例:https://gist.github.com/Xeoncross/bae6f2c5be40bf0c6993089d4de2175e

    【讨论】:

      猜你喜欢
      • 2017-10-05
      • 1970-01-01
      • 2019-08-28
      • 2016-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-16
      • 2015-03-29
      相关资源
      最近更新 更多