I'm wondering what is the default Django policy for CSRF generation? Are they created per page or per session? And if it is per session, why is it chosen? Isn't it less secure than per-page CSRF?
Are they created per page or per session?
From Django's official documentation:
A CSRF cookie that is based on a random secret value, which other sites will not have access to.
This cookie is set by CsrfViewMiddleware. It is sent with every response that has called django.middleware.csrf.get_token() (the function used internally to retrieve the CSRF token), if it wasn’t already set on the request.
In order to protect against BREACH attacks, the token is not simply the secret; a random salt is prepended to the secret and used to scramble it.
For security reasons, the value of the secret is changed each time a user logs in
That means the secret
used to generate the CSRF tokens is generated per-session
(kind of).
When validating the ‘csrfmiddlewaretoken’ field value, only the secret, not the full token, is compared with the secret in the cookie value. This allows the use of ever-changing tokens. While each request may use its own token, the secret remains common to all.
This check is done by CsrfViewMiddleware.
That means if we want, we can generate different CSRF token according to our needs (e.g. per-page
) but the secret will remain the same.
You might want to read Radwan's answer as well.