I was working with Django to create a website and got some questions about CSRF. I use django.middleware.csrf.CsrfViewMiddleware
and add <form action="" method="post">{% csrf_token %}
in my POST form.
And when I test the website:
GET / HTTP/1.1
Host: 123.207.137.168:8000
Then, I got cookies
Set-Cookie:csrftoken=Ev8veOH89vFDnG3a0GJUsMXA1oGZXxqXRw2nFWiKrvZ9UE10niTlZCiOxdnoKfTv; expires=Thu, 27-Dec-2018 06:37:41 GMT; Max-Age=31449600; Path=/
But in the html:
<input type='hidden' name='csrfmiddlewaretoken' value='JswHLk4fNpxHkh0OObD1uKiOxSDUzkMDWtqzcsFR5pRdRfYEbNNs1AD23Hkjm2fb' />
So I was wondering why the csrftoken
and csrfmiddlewaretoken
is different and how did the server use these two value to valid if the request is from the users or hackers?
There are some answers in the docs, but looking at the code really solves this "mystery" Basically what django does is the following:
Now when you make a POST request for example, the following happens
This method with the two tokens is called Double-Submit Cookie. Django's way with the salting allows to keep the same csrf secret for some time without having to renew the key for every request
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