Django 是否使用每页或每会话 CSRF?

Does Django use per-page or per-session CSRF?

我想知道生成 CSRF 的默认 Django 策略是什么?它们是按页面还是按会话创建的?如果是每个会话,为什么选择它?它不是比每页 CSRF 更安全吗?

Are they created per page or per session?

来自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

这意味着用于生成 CSRF 令牌的 secret 已生成 per-session(种类)。


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.

这意味着如果我们愿意,我们可以根据需要生成不同的 CSRF 令牌(例如 per-page),但秘密将保持不变。

您可能还想阅读

通读 Django's Official Documentation about CSRF 真的很有帮助

它解释了它是如何作为中间件在内部工作的,如果你转到这个section,第 3 点

For all incoming requests that are not using HTTP GET, HEAD, OPTIONS or TRACE, a CSRF cookie must be present, and the ‘csrfmiddlewaretoken’ field must be present and correct. If it isn’t, the user will get a 403 error.

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.

这意味着您可以灵活地为每页生成令牌。

如果您的要求强制在每个 request/page、结帐 this question and its answers 上生成新的 csrf 令牌,它们真的很有帮助。