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
