简体   繁体   中英

Redirect user to previous page after authentication

I'm using Google auth through Passport in my app and I'm attempting to redirect the user back to the original page they requested after successful sign-in. I think that location.reload() may be the problem, but not sure how to solve it.

routes.js:

router.post('/auth/google/return', passport.authenticate('google'), function(req, res) {
  res.redirect(req.session.returnTo);
  req.session.returnTo = null;
});

middleware.js:

var isAuth = function(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  } else {
    req.session.returnTo = req.url;
    return res.redirect('/');
  }
};

called on button click:

$.post('/auth/google/return', {code: authResult.code, access_token: authResult.access_token}).done(function(data) {
    location.reload();
});

Try:

router.post('/auth/google/return', passport.authenticate('google'), function(req, res) {
   var backURL = req.header('Referer') || '/';
   res.json({redir: backURL});
});

And:

$.post('/auth/google/return', {code: authResult.code, access_token: authResult.access_token}).done(function(data) {
    window.location.href = data.redir;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM