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

前端 未结 4 1089
被撕碎了的回忆
被撕碎了的回忆 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 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);
    });
    

提交回复
热议问题