Expressjs cookie-session settings not working with Passportjs

1.8k Views Asked by At

I'm trying to call my /auth/user endpoint to get the current user that's logged into my website. But because of the new Chrome update I need to somehow set 'sameSite' and 'secure'. Anyone know of how I can get around this? Am I doing something wrong with cookie-session?

The cookie gets sent by express just fine, but it doesn't come with sameSite and secure settings that I specify in the cookie-session settings (see image). I tried with express-session as well, but for some reason the sameSite and secure settings never propogate to cookie used for oauth.

Btw, the authentication works on localhost addresses, but when I deploy from frontend and backend with heroku, I encounter the issue where I need to set sameSite. Would setting up a proxy or something get around the sameSite issue?

enter image description here

2

There are 2 best solutions below

1
On

I am working on the same issue. SameSite=None needs the cookie to be secure

https://www.chromestatus.com/feature/5633521622188032

Eventhough I have set "secure: true" I am still seeing the cookie not being created on Chrome, but I do see it on Edge

0
On

After 3 days trying to figure It out. I finally found a way around this issue, It's not a fix, I'm quite sure PassportJS will come with a solution for that eventually, but for now It allowed me to get the user from the authentication.

Since we are not being able to get the user from the cookie, but the information is in the server session, the way to get this information is to add to the 'server.js' a route to get the user directly from the server session:

app.get('/api/getUser', (req, res) => {
  res.json(req.session.user);
});

For some reason, I suppose the lack of cookie somehow, using the req.session inside of a router is returning undefined, but If used inside 'server.js' (or your server index file) It gets the session.

If you need the req.user._id or some other sensitive information for other requests, I would recommend returning a jwtToken with this information to the frontend (in res.json), then save the token directly in localStorage and pass the token in the body of your requests, is not the ideal, but It's the safer way I could think to keep the ids safe.

I hope It can help you!