liveBook · Manning

CsrfTokenRequestAttributeHandler

As explained in Spring Security in Action, Second Edition

CsrfTokenRequestAttributeHandler is a Spring Security implementation that exposes a generated CSRF token as an HTTP request attribute.

CsrfTokenRequestAttributeHandler exposes a generated CSRF token on the HTTP request. With a configured CsrfTokenRepository, it generates a token for an HTTP GET request and adds the CsrfToken as a request attribute. section 9.3

Use the handler when configuring CSRF protection with a custom token repository:

  • Register the repository with csrfTokenRepository(). section 9.3
  • Set csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler()) in the CSRF configuration. section 9.3
  • Extend the handler when the simple request-attribute behavior requires customization; XorCsrfTokenRequestAttributeHandler provides a more complex default behavior. section 9.3

Generate and submit a token

A GET request obtains the token, while a later POST sends it in X-CSRF-TOKEN. The matching token lets /hello return successfully; omitting it produces HTTP 403 Forbidden. section 9.3

Listing 9.19 The configuration class for the custom CsrfTokenRepository
@Configuration
public class ProjectConfig {

  private final CustomCsrfTokenRepository customTokenRepository;

  // Omitted constructor

  @Bean
  public SecurityFilterChain securityFilterChain(HttpSecurity http) 
    throws Exception {
    
    http.csrf(c -> {
      c.csrfTokenRepository(customTokenRepository);    
      c.csrfTokenRequestHandler(     
        new CsrfTokenRequestAttributeHandler()     #1
      );                                           #1
    });                                            #1

    http.authorizeHttpRequests(
      c -> c.anyRequest().permitAll()
    );

    return http.build();
  }

}

Shows the SecurityFilterChain configuration that combines a custom repository with CsrfTokenRequestAttributeHandler. section 9.3

How Spring Security in Action, Second Edition covers it

How deep it goes
Explains GET-time generation, request-attribute exposure, customization, and testing, but defers handler internals.
Examples
Uses a database-backed repository, GET /hello token retrieval, authenticated-token POST submission, and a missing-token 403 response.
What it assumes
Assumes basic Spring and Java configuration while demonstrating the required CSRF repository wiring.
What you can do after
Configure it in a SecurityFilterChain and test CSRF-protected endpoints with curl.
How it connects
Connects CsrfTokenRepository, CsrfFilter, CSRF protection, and XorCsrfTokenRequestAttributeHandler.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Security in Action, Second Edition. The section links point to the parts of the book it draws on.