0

Context

Hello, I'm in a project where the backend (API) is separate from the frontend and I'm having problems with cookies in cross-site, I read some questions on Stackoverflow like this set-cookies-for-cross-origin-requests, but the solution didn't work for me.

Problem

The frontend is made in React and uses axios to perform the request and the universal-cookie to set cookies, however in the production environment the cookie is not being sent through the request, while in the development environment where Sec-Fetch-Site is same site (because both are on localhost), the cookie is successfully sent on the request.

The backend is made in PHP and makes use of a middleware cors lib to handle CORS.

Request that does not send the cookie

enter image description here

Storage - cookie does not working

Request that correctly sends the cookie

Request - cookie is working

Storage - cookie is working

Tests

Assuming the frontend is on the frontend.com domain and the backend on backend.com, I made the following changes I found on the internet and it didn't work:

  • I configured the backend to return in its response header

    • Access-Control-Allow-Credentials: true and
    • Access-Control-Allow-Origin: https://frontend.com and
    • Access-Control-Allow-Headers: X-Requested-With, Content-Type, Accept, Origin, Authorization
  • I configured axios on the frontend with axios.defaults.withCredentials = true

  • On the frontend I set the cookie with the same-site: none, secure: true and path: /

Note 01: The cookie is visible in the browser's storage, but in the request it is not sent.

Note 02: The only thing I noticed in the request that works for the request that doesn't work even though both have the cookie stored in the browser's storage is that in the request that the cookie does not appear in the request, the Sec-Fetch-Site header is the same to cross-site, while in the request that works the Sec-Fetch-Site header is equal to same-site.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Igor AC
  • 57
  • 1
  • 5
  • 1
    Cookie are not send for different domains than the one they were set for, and no CORS or other settings will change that. – CBroe Apr 29 '22 at 09:33
  • @CBroe in my use case, where I need the client to send the cookie value in every request for the backend (api) to use that value, do you think using a custom header (`X-Endpoint`) would be a good approach? – Igor AC Apr 29 '22 at 11:57
  • Did you solve this problem ? @IgorAC – Hussam Khatib Sep 26 '22 at 07:07
  • @HussamKhatib yes, I had to use custom headers instead of the cookie. – Igor AC Sep 26 '22 at 11:27

0 Answers0