jaredhanson / passport

Simple, unobtrusive authentication for Node.js.
https://www.passportjs.org?utm_source=github&utm_medium=referral&utm_campaign=passport&utm_content=about
MIT License
22.78k stars 1.24k forks source link

passport.authenticate not calling next middleware when authentication fails #224

Open pauliew opened 10 years ago

pauliew commented 10 years ago

I have no login page but rather login appears on every page. I want to redirect user back to the same page they were on regardless of whether authentication was successful (with appropriate flash messages)

Take the following code:

app.post('/login', validateLogin, passport.authenticate('local-login'), function(req, res) {

    var redirectUrl = '/'; 

    if(req.body.to.length > 0){
        redirectUrl = req.body.to;  
    }

    console.log("JUST BEFORE REDIRECT");
    res.redirect(redirectUrl);
});

I only see the final middleware above being called if authentication is passed. If it fails then passport appears to be redirecting me to /login in the form of a get request. In my app this page doesn't exist.

If I pass an additional options object as a parameter in the passport authenticate function then this works:

app.post('/login', validateLogin, passport.authenticate('local-login', {

successRedirect : '/', // redirect to the secure profile section
    failureRedirect : '/signup', // redirect back to the signup page if there is an error
    failureFlash : true, // allow flash messages

}

));

But in doing this I lose the ability to choose where to redirect the user to. It seems that passport takes control over where the user is redirected to if authentication fails. How can I fix this? Or is it a bug? Must passport authenticate be the last middleware in the chain if authentication fails?

Freyert commented 8 years ago

Try using the failWithError option. It's not documented, but you can see an example in #458. Close this issue if this solves your problem.