CRSF LazyCsrfTokenRepository 是如何工作的?

How does CRSF LazyCsrfTokenRepository work?

Java 8 - spring 4.3.x

在配置 spring 安全和启用 csrf 功能时,我遇到了 CsrfTokenRepository 的两种实现方式,一种是惰性的,另一种是基于 Cookie 的

我知道 CookieCsrfTokenRepository 使用将 csrf 令牌写入 cookie 并接受 header 中的 cookie 值来验证有效请求

有人可以帮助我了解 LazyCsrfTokenRepository 是如何工作的吗?

来自javadoc

A CsrfTokenRepository that delays saving new CsrfToken until the attributes of the CsrfToken that were generated are accessed.

为什么会这样? 在 Spring 安全的早期版本中,HttpSessionCsrfTokenRepository 是默认的。这样做的缺点是它总是创建一个令牌,触发会话创建,无论是否使用令牌,这在某些应用程序中可能是浪费。

另一方面,LazyCsrfTokenRepository 仅创建一个包装器,并且仅在调用 getToken() 时才创建实际令牌(例如生成表单时)。这避免了不必要的会话创建。

LazyCsrfTokenRepository 的一个陷阱是,实际的令牌生成仍然必须在 HTTP 响应 提交 之前发生,否则会出现异常。如果您对此有疑问,最简单的方法是(仅)使用其他两种实现方式之一。