3

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.

sureshvv
  • 4,234
  • 1
  • 26
  • 32

2 Answers2

1

You haven't mentioned how you're getting the csrftoken from the server in the first place, so I'm assuming it's already present in your browser. Along with the X-CSRFToken header, also include the cookies in the request using withCredentials: true. I'm using the js-cookie library to get the csrftoken from the cookies.

import Cookies from 'js-cookie';

axios({
    url: 'http://localhost:8000/graphql',
    method: 'post',
    withCredentials: true,
    data: {
        query: `
            {
                // Your query here
            }     
        `
    },
    headers: {
        "X-CSRFToken": Cookies.get('csrftoken')
    }
})

Also add CORS_ALLOW_CREDENTIALS = True to your settings.py, assuming you are using django-cors-headers. Otherwise, the cookies won't be accepted.

Anubhav Das
  • 940
  • 1
  • 11
  • 16
0

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.

mattes
  • 8,936
  • 5
  • 48
  • 73
  • django-cors-headers does this. Actually the header is being sent. It is the cookie that is not. Despite being displayed in the Request headers in chrome devtools. – sureshvv May 03 '19 at 18:30