CsrfToken only valid after page refresh - Django

I got confused with a strange issue with Jango CSRF tokens in my SPA.

When rendering my application, I make sure the token is set with ensure_csrf_cookie

. When I check my cookies I can see what csrftoken

is being stored correctly and I also send it as part of the request using:

     headers: {
       โ€˜X-CSRFTokenโ€™: getCsrfTokenFromCookie(),
     }

      

When I delete the cookie csrftoken

and refresh the page a new one is set csrftoken

, but when I try to submit my request I get the error

message: "CSRF Failed: CSRF token is missing or invalid."

But if I refresh the page again, the request is sent with the same csrfToken cookie!

I'm not sure what is causing this inconsistency. Any thoughts?

+3


source to share


2 answers


Your problem might be similar to this question. If you force the entire page to refresh, the problem may be resolved.



+1


source


I believe this problem was very specific to my application. With React / Redux framework and Django REST, the problem was revealed that when the request was instantiated, the csrfToken was not set yet.



0


source







All Articles