Passport.js always executing “failureRedirect”

时光怂恿深爱的人放手 提交于 2019-12-06 09:49:33

问题


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

回答1:


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());



回答2:


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




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/31407425/passport-js-always-executing-failureredirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!