I'm using Django Rest Framework
and also django-rest-auth
.
I've the standard API endpoints (/login, /logout, /registration...)
With my browser, I can login/list my users/logout. With Insomnia (a API requester), I can't login/logout, I've the error
"CSRF Failed: CSRF token missing or incorrect"
Maybe I need to add the CSRF header, but honestly I don't know where to find this CSRF token... Maybe I need to add some things (@csrf_protect
?) to login endpoint, but am I forced to rewrite completely the default view ?
Solution
You need to set the X-CSRFToken in the Header settings of Insomnia (https://support.insomnia.rest/article/49-cookies ).
X-CSRFToken
cookie
, click on Request => Cookie
Request => Cookie
csrftoken
into Cookie Nameand try it again.
Explanation
The CSRF Token is set by Django in the cookie. This is done within the first request to the server. Then the value of the cookie is send back to the server within the heaader as X-CSRF-Token.
You can see whats going on in the debugger of your browser (F12 in Chrome)
csrftoken Cookie is set
csrftoken is send back as X-CSRF-Token to the server within the Request Header
Mentioning as an answer rather than a comment because of low reputation.
Adding an entry named X-CSRFTOKEN
works. But for that to work, make sure you have some urls which don't require csrftoken and make a request. The solution will only work after making a successful request to the API, or else Insomnia doesn't get the token from the server and No cookies in store for URL
error will appear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With