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

前端 未结 4 1084
被撕碎了的回忆
被撕碎了的回忆 2020-12-14 11:53

I have no login page but rather I have a login form that appears on every page. I want to redirect user back to the same page they were on regardless of whether authenticati

相关标签:
4条回答
  • 2020-12-14 11:57

    I know this might still be a problem for some people like me who tried all the suggested options without any success.

    In my case, as it turned out, I was getting the error because my req.body object was always empty. I had my body parsing middleware set up correctly so it didn't make sense why this was happening.

    After more research I found out that the enctype I was using for my forms(multipart/form-data) isn't supported by body-parser - see their read me - after switching to a different middleware, multer, everything worked smoothly.

    0 讨论(0)
  • 2020-12-14 11:59

    Full answer, including:

    • Middleware to set redirectUrl
    • Flash messages
    • Not returning values that won't be used

    Just create a redirectTo value in your loginRequired middleware:

    var loginRequired = function(req, res, next) {
        if ( req.isAuthenticated() ) {
            next();
            return
        }
        // Redirect here if logged in successfully
        req.session.redirectTo = req.path;
        res.redirect('/login')
    }
    

    And then in your login POST:

    router.post('/login', function(req, res, next) {
        passport.authenticate('local', function(err, user, info) {
            if ( err ) {
                next(err);
                return
            }
            // User does not exist
            if ( ! user ) {
                req.flash('error', 'Invalid email or password');
                res.redirect('/login');
                return
            }
            req.logIn(user, function(err) {
                // Invalid password
                if ( err ) {
                    req.flash('error', 'Invalid email or password');
                    next(err);
                    return
                }
                res.redirect(req.session.redirectTo || '/orders');
                return
            });
        })(req, res, next);
    });
    
    0 讨论(0)
  • 2020-12-14 12:07

    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');
                });      
            }
    ); 
    
    0 讨论(0)
  • 2020-12-14 12:15

    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);
    });
    
    0 讨论(0)
提交回复
热议问题