You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java 8-Spring 4.3.x下LazyCsrfTokenRepository如何工作?

Understanding LazyCsrfTokenRepository in Spring Security

Great question! Let’s break down how LazyCsrfTokenRepository works, especially since you already have context on CookieCsrfTokenRepository.

Core Idea: Lazy Token Generation

Unlike CookieCsrfTokenRepository which generates and sends a CSRF token on the first request (even for safe methods like GET), LazyCsrfTokenRepository follows a "lazy" approach: it only creates and exposes a CSRF token when it’s actually needed.

Step-by-Step Workflow

Here’s how it behaves in typical scenarios:

  • Safe HTTP methods (GET, HEAD, OPTIONS, TRACE): These requests don’t require CSRF validation by default. LazyCsrfTokenRepository won’t generate a token for them—no token is written to a cookie, and no token is exposed via request attributes or endpoints like /_csrf.
  • Non-safe HTTP methods (POST, PUT, DELETE, PATCH): When a client sends one of these requests, Spring Security checks for a valid CSRF token. If no token exists yet, LazyCsrfTokenRepository will:
    1. Generate a new CSRF token.
    2. Delegate to its underlying repository (by default, CookieCsrfTokenRepository) to store the token (usually in a cookie).
    3. Validate the token sent by the client (in a request header, form parameter, etc.) against the stored token.
  • Explicit token retrieval: If your frontend actively fetches the CSRF token (e.g., via the /_csrf endpoint to include in AJAX headers), this will also trigger token generation and storage.

It’s a Decorator, Not a Standalone Repository

LazyCsrfTokenRepository is a decorator pattern implementation. It doesn’t handle token storage or validation on its own—it wraps another CsrfTokenRepository (you can specify which one, but the default is CookieCsrfTokenRepository). All the heavy lifting (token creation, saving to cookie, loading for validation) is done by the underlying repository; LazyCsrfTokenRepository just controls when these actions happen.

When to Use It?

This implementation is ideal for scenarios where:

  • Most of your application’s traffic is made up of safe, read-only requests (like content viewing).
  • You want to avoid unnecessary cookie writes and token generation for requests that don’t need CSRF protection, reducing overhead for both server and client.

Example Configuration

Here’s how to set up LazyCsrfTokenRepository in a Spring Security config:

@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf
                // Use LazyCsrfTokenRepository with default CookieCsrfTokenRepository as delegate
                .csrfTokenRepository(LazyCsrfTokenRepository.withDefaultRepository())
            );
        return http.build();
    }
}

Key Difference from CookieCsrfTokenRepository

AspectCookieCsrfTokenRepositoryLazyCsrfTokenRepository
Token Generation TimingEager (on first request)Lazy (on demand only)
Underlying StorageCookieSame as delegate (default: Cookie)
Overhead for Safe RequestsCookie written on first GETNo cookie until token is needed

内容的提问来源于stack exchange,提问作者d-man

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 06:55:09