Configuring CSRF protection for secure forms means keeping Spring Security's default token-based defense enabled, ensuring the token reaches every form and AJAX call, and layering on complementary browser protections like SameSite cookies.
Key Points: • CSRF is enabled by default in Spring Security for session-based (browser) applications; disabling it should be reserved for stateless APIs. • CookieCsrfTokenRepository can expose the token as a readable cookie so JavaScript-driven SPAs can attach it to AJAX headers. • Server-rendered forms should include the CSRF token as a hidden input field, which Thymeleaf/JSP integrations handle automatically. • SameSite=Strict or Lax cookie attributes add another layer of defense by preventing cookies from being sent on cross-site requests. • The token must be validated on every state-changing (POST/PUT/DELETE) request, not just login.
Example: A Thymeleaf-rendered form automatically includes a hidden _csrf field via Spring's tag support, so the token is submitted with the form and validated on the server before the request is processed.
Code Example:
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()));
return http.build();
}Interview Tip: A concise interview answer is:
"I'd keep CSRF protection enabled and use CookieCsrfTokenRepository so both server-rendered forms and AJAX calls can attach the token correctly. I'd also set SameSite cookie attributes as an additional layer, since that alone blocks most cross-site request forgery attempts even before the token check runs."