You are building a web application that requires secure forms to prevent Cross-Site Request Forgery (CSRF) attacks. How would you configure CSRF protection in Spring Security, and what additional measures would you take to ensure form security?

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

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.

@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.

Last updated: 16 July 2026

Previous question: Your application requires stateless authentication for RESTful services. How would you implement JSON Web Token (JWT) authentication using Spring Security? Describe the flow from user login to accessing protected resources.

Next question: You have a service layer in your application that contains methods that should only be accessed by certain roles. How would you implement method-level security using Spring Security annotations to restrict access to these methods based on user roles?

More Spring Security - Level II interview questions

All Spring Security - Level II questions