CSRF Verification fails in production for Cross Do

2019-07-09 02:13发布

问题:

The HTTP_X_CSRFTOKEN header does not match what is inside the csrftoken cookie.

How can I examine the cookie? Set-Cookie is not displayed in the Response header for Cross Domain requests.

I have already followed instructions found in:

CSRF with Django, React+Redux using Axios

Interestingly I found "X-CSRFTOKEN" translates to "HTTP_X_CSRFTOKEN" on the server request header.

Works fine in the development env under localhost (although I am using 2 different ports - one for django and the other my frontend).

UPDATE:

It seems the csrktoken cookie is not correctly set for cross domain rquests (although the browser displays it in the Request Header) so the X-CSRFTOKEN does not get sent.

I ended up adding an API call to return the current csrftoken using a GET request and then sending it back using the X-CSRFTOKEN header.

回答1:

You will have to make the X-CSRFTOKEN header accessible via the CORS Access-Control-Expose-Headers directive. Example:

Access-Control-Expose-Headers: X-CSRFTOKEN

This header has to be set by your API or web server, so that the browser will see it during the CORS preflight request.