2

I am using using passport to authenticate my users using discord oauth2. I want them to be redirected back to the same page they came from instead of to the home page or a dashboard.

I tried storing the URL in the session like described here, but it doesn't persist to the next request.

Middleware for my pages that need authentication:

module.exports = (req, res, next) => {
  if (req.user) {
    next();
  }
  else {
    req.session.returnTo = req.originalUrl;
    res.redirect('/auth');
  }
};

Auth route:

router.get("/auth", passport.authenticate("discord"));

router.get("/auth/redirect", passport.authenticate("discord", {
  failureRedirect: "/auth/forbidden"
}), (req, res) => {
  console.log(req.session); // doesnt have returnTo inside anymore ?
  res.redirect(req.session.returnTo || '/');
  delete req.session.returnTo;
});

The console.log shows the user successfully authenticated, but the returnTo field is no longer there.

SomeCoder
  • 275
  • 1
  • 19
  • how's your client handling the cookies? Fetch/Axios doesn't send cookies by default – Yosi Leibman Jul 12 '22 at 14:34
  • @YosiLeibman i am not doing anything special, not using fetch or axios or anything. i just have express use session like this https://pastebin.com/bmuDkHED – SomeCoder Jul 12 '22 at 14:56

1 Answers1

9

Hi I ran into the same problem. Try adding keepSessionInfo: true to passport.authenticate.

router.get("/auth", passport.authenticate("discord", {
    failureRedirect: "/auth/forbidden", keepSessionInfo: true
}), (req, res) => {
    console.log(req.session); // doesnt have returnTo inside anymore ?
    res.redirect(req.session.returnTo || '/');
    delete req.session.returnTo;
});
You Qi
  • 8,353
  • 8
  • 50
  • 68
BRizzle
  • 106
  • 3
  • 2
    This is relevant for anyone trying to follow Colt Steele's The Web Developer Bootcamp 2023 on Udemy, as he doesn't use it in his tutorial (It must be something new introduced since the tutorial was originally made). But thank you for answering this! Certainly saved me a lot of frustration. – CSG Jan 12 '23 at 08:42
  • For those that are finding this because your sessions are being replaced, bear in mind this was done to prevent certain security vulnerabilities. If you're going to use `keepSessionInfo` I would recommend you regenerate the sessions manually when a user navigates to your login page to prevent session fixation vulnerabilities. You can do this using `req.session.regenerate()`, you can store and reset the `returnTo` value to keep the functionality. – bendataclear May 06 '23 at 15:27