简体   繁体   English

Passport.js 总是执行“failureRedirect”

[英]Passport.js always executing "failureRedirect"

First of all, I'm very new to Passport.js so maybe this ends up being a very naïve question.首先,我对 Passport.js 很陌生,所以也许这最终会成为一个非常幼稚的问题。 I have this as a strategy for the signup:我将此作为注册策略:

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

And this is how I deal with a POST on /register :这就是我在/register上处理POST

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

This always brings me to the failureRedirect link, instead of the success.总是将我带到failureRedirect链接,而不是成功。 The input data is correct, and I'm always using a different user and mail to register.输入的数据是正确的,我总是使用不同的用户和邮件来注册。 I'm sorry if this is a stupid question, but I don't really understand why it never goes to the successRedirect .如果这是一个愚蠢的问题,我很抱歉,但我真的不明白为什么它永远不会进入successRedirect

Thanks.谢谢。

EDIT: added the suggestion and corrections by @robertklep, still not working.编辑:添加了@robertklep 的建议和更正,但仍然无效。 I'd like to point out that no error is triggered, nor any log printed.我想指出,没有触发错误,也没有打印任何日志。

EDIT2: Serialization/deserialization functions: EDIT2:序列化/反序列化功能:

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

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

I had this same problem, failureRedirect was always being executed我有同样的问题, failureRedirect 总是被执行

First to diagnose, I used the custom callback method http://passportjs.org/docs/authenticate首先进行诊断,我使用了自定义回调方法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);
});

Then I could see what the hidden error was然后我可以看到隐藏的错误是什么

authenticate
null
false
{ message: 'Missing credentials' }

Which then became easy for me to diagnoise, I was sending JSON in the request rather than FORM fields这对我来说很容易诊断,我在请求中发送 JSON 而不是 FORM 字段

Fixed by changing通过更改固定

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

To

app.use(bodyParser.json());

A couple of points:几点:

the function function(req, name, password, email, done) is wrong.函数function(req, name, password, email, done)是错误的。 the verify function signature is function(req, username, password, verified) when the passReqToCallback flag is on.passReqToCallback标志打开时function(req, username, password, verified)验证函数签名是function(req, username, password, verified)

you're not providing serialization/deserialization functions.您没有提供序列化/反序列化功能。 This is probably not biting you at the moment but could later on.这可能目前不会咬你,但以后可能会咬你。

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

what I also find interesting is that you use the authenticate function to actually create a user.我还发现有趣的是,您使用authenticate功能来实际创建用户。 I'd probably create the user and then call passport.login to make them authenticated.我可能会创建用户,然后调用passport.login 来验证他们的身份。

Just my 2 pence :-)只是我的 2 便士 :-)

do you use http or https ?你使用 http 还是 https ? I had the same situation.我有同样的情况。 I fixed it like this我是这样修的

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

In my situation passport can't receive cookies.在我的情况下,护照无法接收 cookie。

I know this is almost 4 years old, but in case someone runs into the same issue, I used the diagnose from djeeg我知道这已经快 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); });

and I got: null false 'missing credentials'我得到:null false 'missing credentials'

THE SOLUTION: It turns out I had not used the "name" in my HTML form which meant data wasn't read and that's where the error came from解决方案:原来我没有在我的 HTML 表单中使用“名称”,这意味着没有读取数据,这就是错误的来源

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

That fixed it for me那为我修好了

试试检查你的表单的方法,它必须是method = post,以防我错误地把它写成GET方法,花了我3天时间才找到这个,因为没有错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM