Auth0 Home Blog Docs

Passport doesn't log user in in production but does redirect

Hey, I’m finishing up a deployment to AWS Elastic Beanstalk. I’m running a Node Express server. At the callback endpoint, I have this code:

router.get('/callback', (req, res, next) => {
  passport.authenticate('auth0', (err, user, info) => {
    if (err) return next(err);
    if (!user) return next(JSON.stringify(info));

    req.logIn(user, err => {
      if (err) return next(err);

      const { returnTo } = req.session;
      delete req.session.returnTo;
      res.redirect(returnTo || clientRootURL + '/callback');
    });
  })(req, res, next);
});

This is exactly what the docs say and it works perfectly fine on localhost. In production, it seems to work fine: when I log in, it redirects me to that endpoint, goes through the process and redirects me back to the front end. But then on a subsequent request, I get req.user as undefined. Somehow, passport doesn’t log the user in, even though it does on localhost.

I tried adding some console logs to all the points where it could fail, I know for a fact that it runs through to completion all the way to res.redirect. Yet somehow, req.user stays at undefined.

Does anyone have any idea what’s going wrong or how I should debug this?

UPDATE: I realized what might be the problem. The server runs on an AWS subdomain and I have a custom domain pointing to it. When logging in, I have the redirect URI set directly to the AWS subdomain. Later though, I’m reaching out to the custom domain for information. So I log in on one domain and then try to use that log in cookie on another domain, both of which are actually pointing to the same server.

Just in case, here’s my session configuration:

secret: 'nottherealsecret',
cookie: {
  sameSite: false
},
resave: false,
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: mongoose.connection })

UPDATE 2: I tried adding cookie.domain = “mydomain”, didn’t work. Also, I feel like I should clarify why I’m using one domain for logging in and another domain for everything else. I need to log in on the domain where the server actually runs because otherwise, I get an error saying the redirect URL is not what was expected. But that domain doesn’t have HTTPS and there’s no way to set it up to have it so I need that custom domain for all my fetch calls to avoid mixed origin errors.

TL;DR: I have one instance of one server running on two domains, one of which is just pointing to the other one. I need to be able to log in on one of them and stay logged in when using the other one. Setup: Node, Express, Passport.js, AWS Elastic Beanstalk