CSRF Verification fails in production for Cross Domain POST request

北城以北 提交于 2019-12-01 22:07:48

问题


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.




回答2:


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.



来源:https://stackoverflow.com/questions/55842141/csrf-verification-fails-in-production-for-cross-domain-post-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!