2

I am building a node express rest app with react frontend. At development the backend is running at localhost:5000 and the frontend at localhost:3000. I am using session based authentication system. So I am sending a Set-Cookie header when authentication is successful from the backend. But the problem is that since the frontend and the backend area on different domains the cookie cannot be set. What can be done?

Plus, I do not want to use the JWT for authentication for the reasons laid out at http://cryto.net/~joepie91/blog/2016/06/13/stop-using-jwt-for-sessions/

Middleware

const cors = require('cors');
app.use(cors({ credentials: true, origin: 'http://localhost:3000' }));

Following is the header sent back from the backend

Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 129
Content-Type: application/json; charset=utf-8
Date: Sun, 22 Dec 2019 14:24:03 GMT
ETag: W/"81-RZ35EekMxvCHWWNZ8hxPVFlS+R8"
Set-Cookie: connect.sid=s%3Afa5CxZSLQznDHuO7I6y9qAfy5-VuezUj.I%2F3BP6vfXybkyUXej6%2Fjt5ribqmmfoy1NQfSImuNYaU; Path=/; Expires=Sun, 29 Dec 2019 14:24:03 GMT; HttpOnly
Strict-Transport-Security: max-age=15552000; includeSubDomains
Vary: Accept-Encoding
X-Content-Type-Options: nosniff
X-DNS-Prefetch-Control: off
X-Download-Options: noopen
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Kucl Stha
  • 565
  • 1
  • 6
  • 20
  • You can register a CORS middleware as long as you environment is DEV. You can use https://expressjs.com/en/resources/middleware/cors.html to set the CORS headers to '*'. Please note that for security reasons this middleware should set '*' only while you are in DEV or debugging. – dima golovin Dec 22 '19 at 14:05
  • @dimagolovin Thank you for your response. But I am new to this. How can I set it? I added app.use(cors()) but still does not work – Kucl Stha Dec 22 '19 at 14:21
  • read this section - https://expressjs.com/en/resources/middleware/cors.html#configuring-cors-w-dynamic-origin you can add your localhost with different ports to the whitelist – dima golovin Dec 22 '19 at 14:46
  • @dimagolovin I used app.use(cors({ credentials: true, origin: 'http://localhost:3000' })); and also did as you taught but still does not work, I think there is mistake in other place in my code. – Kucl Stha Dec 22 '19 at 14:50
  • Found the answer here https://stackoverflow.com/questions/46288437/set-cookies-for-cross-origin-requests – Kucl Stha Dec 22 '19 at 14:56

0 Answers0