Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a CSRF token from the command line?

I'm frequently testing my application using curl and in the past I've had to simply wrap my views with csrf_exempt. I really don't want to do this, as I have a nasty feeling that I'll forget to do this in deployment and enjoy a lifetime of CSRF hell.

Is there a way for me to request a CSRF token using Django's shell commands? I'd like to get a token I could send with my curl requests to test things safely.

like image 350
Naftuli Kay Avatar asked Nov 07 '13 02:11

Naftuli Kay


2 Answers

Make an initial GET request to the form URL in order to fill the cookie jar:

$ curl http://example.com/some-form/ -o /dev/null -c cookies.txt -s

Get the value of the csrftoken cookie:

$ grep csrftoken cookies.txt | cut -f 7
YQkfXZCKtPP0hC30NmH10jSWuf6yJA5E

When issuing a POST, just include a csrfmiddlewaretoken field with this value (and use the same cookie jar).

I use the same trick to write end-to-end tests using the requests library.

like image 96
Paulo Scardine Avatar answered Nov 04 '22 04:11

Paulo Scardine


you can do like this

from django.middleware.csrf import _get_new_csrf_key()
request.META["CSRF_COOKIE"] = _get_new_csrf_key()
like image 28
Surya Avatar answered Nov 04 '22 06:11

Surya