issue with cross-site cookies: how to set cookie from backend to frontend issue with cross-site cookies: how to set cookie from backend to frontend google-chrome google-chrome

issue with cross-site cookies: how to set cookie from backend to frontend


I will try to give the concept.

First please know that I'm using a Backend which is developed from SailsJS and a Frontend which is developed from AngularJS and Apps that connect to backend which are developed from using Angular9.

I am using http only cookie for the frontend (a CMS) to grant permission to add content to users that are logged in. HTTP only cookie will be set to them on authentication success.

Please note that there is a tricky part to http cookies and backend and frontend both serve different URLs just like in the scenario presented.

Points:

  1. So when in development you have to host your backend and frontend under same IP.ex. my backend : 192.168.8.160:1337, frontend: 192.168.8.160:81.different ports same ip.

  2. this is not the scenario when it goes to production you can have any domain :)

  3. you have to allow CORS in backend and have your frontend ip:port under accepted origins.

  4. Implementation, you have to identify your environment, in my case,

if (sails.config.environment === 'development'){  res.setHeader('Set-Cookie',[`token=${token};  Path=/;HttpOnly; maxAge=86400000;SameSite=false;`]);} else {  res.setHeader('Set-Cookie',[`token=${token};  Path=/;HttpOnly; maxAge=86400000;SameSite=None;Secure=true;`]);}

Please note in above code in development environment you need SameSite=false therefore you need to have the same ip because we cannot have SameSite=None because it would require to have Secure=true and it would then require HTTPS. It would be a headache to achieve it in development mode.

That's it folks. If you get this right you can achieve this.


You can completely disable this feature by going to "chrome://flags" and disabling "Cookies without SameSite must be secure". However, this will disable it for all sites, so it will be less secure when you aren't developing too.