Wednesday, June 30, 2021

Re: In django you can either obtain a `csrftoken` from a cookie or the form can generate a nonce `csrftoken`. How does django validate both?

Django does not store csrftoken on the server.

Django provides the csrftoken in two places: 1) The cookie; 2) A hidden form field.

When the browser makes a POST request, then:

  1. It sends back the cookie anyway (that's what cookies do)
  2. It submits the csrftoken as a form field (or as the X-CSRFToken HTTP header in case of AJAX).

All Django does after that is verify that the token it receives with (2) is the same as the token it receives with (1).

Why this helps? Because the attack it is designed to mitigate is one where you visit which contains the following:

<form method="post" target="">
    <input type="hidden" name="somename" value="somevalue">
    <!-- More hidden fields that, if submitted successfully to, will cause data loss or other problem -->
    <input type="submit" value="A message that pretends that when you click here something else is going to happen">

For this attack to succeed, would need to specify a csrftoken as, say, a hidden form field (which is possible) AND provide the same token through a cookie. This is not possible. can't set cookies of another site. The post request may indeed send a csrftoken as a cookie to, but this will be the csrftoken received the previous time the user visited It will not be the same as the csrftoken sent as a hidden field, because can't read cookies of another site, so it can't possibly read that cookie and set the hidden field to its value.

Antonis Christofides  +30-6979924665 (mobile)

On 30/06/2021 15.14, Patrice Chaula wrote:
In django you can either obtain a `csrftoken` from a cookie. Or the form can generate a nonce `csrftoken`. How does django validate both and where are they stored on the server. Are they stored as part of the session?
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
To view this discussion on the web visit

No comments:

Post a Comment