reactjsdjangocookiescsrf-token

CSRF error when making POST request to Django API


I am currently developing an application that has a React JS front end and Python Django backend. After successfully logging in, the backend created the necessary cookies, which includes the CSRF token, however when the front end makes a POST request the API returns an error with: "CSRF Failed: CSRF token missing or incorrect" even though the CSRF token is within the cookies that are passed to the API.

I have looked online and the fix is to include the CSRF token in the X-CSRFToken header, which I have successfully tested by manually putting the CSRF token in the front end code when it makes the API call.

When I try to use Cookies.get('csrftoken'), or even just console.log(document.cookie), it does not return anything because the domain of the CSRF token is the backend URL and therefore different to the front end domain so it does not let me use it within the frontend code.

Is there a way for me to use the CSRF token in the cookie to validate the request within the API or can I somehow access it within the frontend to pass it via the X-CSRFToken header even though it is a different domain?


Solution

  • I found the solution! In settings.py, you can write the following:

    CSRF_COOKIE_DOMAIN = "domain"

    I set domain to the same domain as the frontend, and was therefore able to access it in the frontend code to pass back to the API via the X-CSRFToken header