How to Disable CSRF Protection in Spring Security
To disable
CSRF protection in Spring Security, configure your security filter chain bean and call csrf().disable() on the HttpSecurity object. This turns off CSRF checks, which is useful for APIs or non-browser clients.Syntax
Use the HttpSecurity object in your security configuration and call csrf().disable() to turn off CSRF protection.
http: the security configuration objectcsrf(): accesses CSRF configurationdisable(): disables CSRF protection
java
http.csrf().disable();
Example
This example shows a complete Spring Security configuration class that disables CSRF protection using the modern SecurityFilterChain bean approach.
java
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf().disable() // Disable CSRF protection .authorizeHttpRequests(auth -> auth .anyRequest().authenticated() ) .httpBasic(); return http.build(); } }
Output
Spring Security starts without CSRF protection; all requests require authentication with HTTP Basic.
Common Pitfalls
Disabling CSRF can expose your app to security risks if used incorrectly. Common mistakes include:
- Disabling CSRF for web apps that use cookies and forms, which can allow attackers to perform unwanted actions.
- Using the older
WebSecurityConfigurerAdapterclass, which is deprecated since Spring Security 5.7. - Not understanding when to disable CSRF: it is safe to disable for stateless APIs using tokens but not for traditional web apps.
java
/* Wrong (legacy) approach - deprecated class */ //@Configuration //public class SecurityConfig extends WebSecurityConfigurerAdapter { // @Override // protected void configure(HttpSecurity http) throws Exception { // http.csrf().disable(); // } //} /* Right (modern) approach */ @Configuration public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf().disable(); return http.build(); } }
Quick Reference
- Use
csrf().disable()insideSecurityFilterChainbean. - Safe to disable for stateless REST APIs.
- Do NOT disable for web apps with sessions and forms unless you understand the risks.
- Use modern configuration with
SecurityFilterChain, not deprecated adapters.
Key Takeaways
Disable CSRF by calling csrf().disable() on HttpSecurity in a SecurityFilterChain bean.
Use this only for stateless APIs or non-browser clients to avoid security risks.
Avoid deprecated WebSecurityConfigurerAdapter; prefer SecurityFilterChain configuration.
Disabling CSRF in web apps with sessions can expose vulnerabilities.
Always understand your app's security needs before disabling CSRF.