CORS error when adding "x-csrf-token" request header

I have an API that I access from another port from a JavaScript app. I setup CORS with corsica and everything was working fine.

Recently I try to add CSRF protection and I added the x-csrf-token header (into the JS Fetch API options, see below) and added the :protect_from_forgery plug.

{
  credentials: 'include',
  headers: new Headers({ 'x-csrf-token': csrf })
}

The CSRF token is correct because if I omit it from the request header, I will have a CSRF error.

However, now I have a CORS error:

Access to fetch at ‘http://myapp.localhost:4000/api’ from origin ‘http://myapp.localhost:5000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

When I remove the CSRF plug and CSRF request header (‘x-csrf-token’), I get the responses (CORS is correctly setup).

Any idea why CSRF setup is interfering with the CORS setup?

headers: new Headers({ ‘x-csrf-token’: csrf })

This might be overwriting all your headers, causing the CORS check on your server to fail. You might want to check if your server is receiving the request with the Origin header or anything else it needs to validate the request.

1 Like

Forgot that if you add custom request headers, the header must be whitelisted through the Access-Control-Allow-Headers response header… added "x-csrf-token" into the whitelist.

2 Likes