简体   繁体   中英

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. 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 :

/* 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. 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 .

Thanks.

EDIT: added the suggestion and corrections by @robertklep, still not working. I'd like to point out that no error is triggered, nor any log printed.

EDIT2: Serialization/deserialization functions:

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

First to diagnose, I used the custom callback method 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

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. the verify function signature is function(req, username, password, verified) when the passReqToCallback flag is on.

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. I'd probably create the user and then call passport.login to make them authenticated.

Just my 2 pence :-)

do you use http or 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.

I know this is almost 4 years old, but in case someone runs into the same issue, I used the diagnose from 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'

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

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

That fixed it for me

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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