【问题标题】:Passport.js always executing "failureRedirect"Passport.js 总是执行“failureRedirect”
【发布时间】:2015-10-03 03:17:55
【问题描述】:

首先,我对 Passport.js 很陌生,所以这可能是一个非常幼稚的问题。我将此作为注册策略:

// Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
var LocalStrategy = require('passport-local').Strategy;
var FacebookStrategy = require('passport-facebook');
app.use(expressSession({secret: 'mySecretKey'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());

//[...]

  passport.use('signup', new LocalStrategy({
     name : 'name',
     password : 'password',
     email : 'email',
     passReqToCallback : true 
   },
   function(req, username, password, done) {
     findOrCreateUser = function(){
       // find a user in Mongo with provided username
       User.findOne({'name':username},function(err, user) {
         // In case of any error return
         if (err){
           console.log('Error in SignUp: '+err);
           return done(err);
         }
        // already exists
      if (user) {
            console.log('User already exists');
            return done(null, false,
            req.flash('message','User Already Exists'));
         } else {
           // if there is no user with that email
           // create the user
           var newUser = new User();
           // set the user's local credentials
           newUser.name = name;
           newUser.password = createHash(password);
           newUser.email = req.param('email');
           /*newUser.firstName = req.param('firstName');
           newUser.lastName = req.param('lastName');*/

           // save the user
           newUser.save(function(err) {
             if (err){
               console.log('Error in Saving user: '+err);
               throw err;
             }
             console.log('User Registration succesful');
             return done(null, newUser);
           });
         }
       });
    };

    // Delay the execution of findOrCreateUser and execute
    // the method in the next tick of the event loop
    process.nextTick(findOrCreateUser);
  })
 );

这就是我在/register 上处理POST 的方式:

/* Handle Registration POST */
app.post('/register', passport.authenticate('signup', {
  successRedirect: '/',
  failureRedirect: '/failure_registration',
  failureFlash : true
}));

这个总是把我带到failureRedirect链接,而不是成功。输入数据是正确的,我总是使用不同的用户和邮件进行注册。如果这是一个愚蠢的问题,我很抱歉,但我真的不明白为什么它永远不会转到 successRedirect

谢谢。

编辑:添加了@robertklep 的建议和更正,但仍然无法正常工作。我想指出的是,没有触发错误,也没有打印任何日志。

EDIT2:序列化/反序列化函数:

passport.serializeUser(function(user, done) {
    done(null, user.id);
});

passport.deserializeUser(function(id, done) {
    User.findById(id, function (err, user) {
        done(err, user);
    });
});

【问题讨论】:

  • Passport 的配置和设置需要特定的订单。如果没有关于如何配置 Passport 其余部分的更多信息,很难说出原因可能是什么。查看the various example projects 以确保您的设置看起来相似(尤其是设置策略和 Express 中间件的顺序)。
  • 在问题中添加了配置,大家可以去看看。检查了多个示例,它们或多或少看起来都一样。还是行不通。如果您需要更多代码,我可以提供。
  • 只是为了确定一下,您能否删除process.nextTick()(并将findOrCreateUser() 中的代码上移一级)?这没用。另外,将passport.use('signup', ...) 移动到之前 app.use(passport.*)
  • 感谢您的帮助,很遗憾我应用了您的更改,但他们没有解决问题。

标签: node.js registration passport.js


【解决方案1】:

试试看你表单的method,一定是method = post,以防我误写成GET方法,花了3天才找到,因为没有错误

【讨论】:

    【解决方案2】:

    我知道这已经快 4 岁了,但如果有人遇到同样的问题,我使用了 djeeg 的诊断

    app.post('/sign_in', function(req, res, next) {
        console.log(req.url);
        passport.authenticate('local-login', function(err, user, info) {
            console.log("authenticate");
            console.log(err);
            console.log(user);
            console.log(info);
        })(req, res, next);
    });

    我得到了: 空值 错误的 '缺少凭据'

    解决方案:事实证明我没有在我的 HTML 表单中使用“名称”,这意味着没有读取数据,这就是错误的来源

    <input name="email" type="email">

    这为我解决了问题

    【讨论】:

      【解决方案3】:

      我遇到了同样的问题,failureRedirect 总是被执行

      首先诊断,我使用了自定义回调方法 http://passportjs.org/docs/authenticate

      app.post('/sign_in', function(req, res, next) {
          console.log(req.url);
          passport.authenticate('local-login', function(err, user, info) {
              console.log("authenticate");
              console.log(err);
              console.log(user);
              console.log(info);
          })(req, res, next);
      });
      

      然后我可以看到隐藏的错误是什么

      authenticate
      null
      false
      { message: 'Missing credentials' }
      

      这对我来说很容易诊断,我在请求中发送 JSON 而不是 FORM 字段

      通过更改修复

      app.use(bodyParser.urlencoded({ extended: true }));
      

      app.use(bodyParser.json());
      

      【讨论】:

        【解决方案4】:

        你使用 http 还是 https ?我也有同样的情况。我是这样修复的

        app.use(expressSession({....   
           cookie: {
           httpOnly: true,
           secure: false // for http and true for https
         }
        }));
        

        在我的情况下,护照无法接收 cookie。

        【讨论】:

          【解决方案5】:

          几点:

          函数function(req, name, password, email, done) 错误。当passReqToCallback 标志打开时,验证函数签名为function(req, username, password, verified)

          您没有提供序列化/反序列化功能。这可能暂时不会咬你,但以后可能会。

          passport.serializeUser(function(user, done){
            done(null, user.id);
          });
          

          我还发现有趣的是您使用authenticate 函数来实际创建用户。我可能会创建用户,然后调用 passport.login 以使他们通过身份验证。

          只要我的 2 便士 :-)

          【讨论】:

          • 谢谢,我已经在问题中添加了我已经定义的序列化/反序列化函数。我还删除了电子邮件并将用户名用于findOne 函数。仍然无法正常工作,也没有产生任何日志。
          猜你喜欢
          • 2018-05-13
          • 2014-10-10
          • 2016-01-18
          • 2017-04-18
          • 2012-10-28
          • 1970-01-01
          • 2019-12-15
          • 2020-06-05
          • 1970-01-01
          相关资源
          最近更新 更多