I'm trying to learn about security. I am 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:{'csrftoken': '1effe96056e91a8f58461ad56c0d4ddc', ...
The form's hidden
csrfmiddlewaretoken
:<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.