Here are some additions to Dan's answer. Please, correct me if something is wrong, I am still a bit confused about it myself.
Before we continue, read about CSRF protection in Django. Read it carefully. You need to put the token from the cookie into the header X-CSRFToken
. This will not work if the cookie is Httponly, that is, if you have set CSRF-COOKIE-HTTPONLY = True
in settings.py
. Then you have to embed the cookie in the document which, of course, creates further vulnerabilities and reduces protection the gained by using Httponly
.
As far as I can tell, if the cookie is not Httponly
, jQuery sets X-CSRFToken automatically. Correct me if I am wrong, but I've just spent several hours playing with it, and this is what I am consistently getting. This makes me wonder, what is the point of the advice in Django documentation? Is it a new feature in jQuery?
Further discussion:
Tastypie disables CSRF protection except with Session Authentication, where it has custom code in authentication.py
. You have to pass both the cookie csrftoken
cookie and the header X-CSRFToken
for the authentication to work. (This is Tastypie's requirement.) Assuming same domain, the browser will pass the cookies. JQuery will pass the header for you unless the csrftoken cookie is Httponly. Conversely, if the cookie is Httponly, I was unable to even manually set the header in $.ajaxSetup{beforeSend...
. It appears that jQuery automatically sets X-CSRFToken to null
if the csrftoken
cookie is Httponly. At least I was able to set the header X-CS_RFToken to what I wanted, so I know I passed the value correctly. I am using jQuery 1.10.
If you are using curl
for testing, you have to pass two cookies (sessionid
and csrftoken
), set the headers X-CSRFToken
and, if the protocol is HTTPS, also set the Referrer
.