Trying to learn about security. Curious about why in django when submitting a form (a POST), there are 2 separate "elements" that contain the same csrf token value:
- the csrftoken cookie:
COOKIES:{'csrftoken': '1effe96056e91a8f58461ad56c0d4ddc', ...
- the Form's hidden csrfmiddlewaretoken:
POST:<QueryDict: {u'csrfmiddlewaretoken':
[u'1effe96056e91a8f58461ad56c0d4ddc'], ...
If django is inserting the hidden csrf field/value to the form when it sends it to the browser (GET), and expects the same value back when receiving the POST, then why is it necessary to also set a cookie?
A more general question, if either of them was missing (form, cookie), could you provide a scenario that explains how this could be exploited (security attack)?
By the way, I ran a couple of simple tests to make sure that django was checking the validity of each one separately and indeed it is:
if I change the form's csrf value before doing the POST, I get this debug error back:
CSRF token missing or incorrect
if I delete the csrf cookie before doing the POST, I get a different error back:
CSRF cookie not set.
I'm just familiar with basic csrf concepts and want to learn how django helps protect against these types of attacks.
Thanks,
jd
update:
Although both answers (S.Lott and M. DeSimone) were informative and make sense, I thought that there could be a more detailed explanation for requiring the presence of the security value in both the form and in the cookie. While searching outside stackoverflow.com, I came across a blog post from...Jeff Atwood.
I have included a third answer (sorry to answer my own question but I think that it is relevant supplemental info) that refers to a blog post from Jeff and includes a quotation.