Nodejs and PassportJs: Redirect middleware after passport.authenticate not being called if authentication fails

You could use a custom authentication callback as described in the last paragraph there http://passportjs.org/guide/authenticate/.

app.post('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    // Redirect if it fails
    if (!user) { return res.redirect('/login'); }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      // Redirect if it succeeds
      return res.redirect('/users/' + user.username);
    });
  })(req, res, next);
});

I was running into the same issue where the redirect-calls , that follow successful Facebook Auth

  • passport.authenticate('facebook', ..)

.. were not being honored.

Based on 'local' passportJS Strategy - and a nice reminder of that from @ploutch's answer here .. I realized the key to getting it to work seems to be in this call:

req.logIn(user, function(err) {
 ...
}

For Facebook, this route setup worked for me:

app.get(
        '/auth/facebook/callback',

        passport.authenticate
        (
            'facebook', 
            { failureRedirect: '/fbFailed' }
        ),

        function(req, res) 
        {
            var user = myGetUserFunc(); // Get user object from DB or etc

            req.logIn(user, function(err) {

              if (err) { 
                req.flash('error', 'SOMETHING BAD HAPPEND');
                return res.redirect('/login');
              }

              req.session.user = user;

              // Redirect if it succeeds
              req.flash('success', 'Fb Auth successful');
              return res.redirect('/user/home');
            });      
        }
);