How to disable CSRF in Spring Security
- Details
- Written by Nam Ha Minh
- Last Updated on 05 July 2024   |   Print Email
You know, Spring Security enables CSRF (Cross Site Request Forgery) protection to prevent CSRF attack that forces a legitimate user submits a malicious request to the server. Spring Security eliminates this kind of exploit by generating a unique token in each web form and verifying each form submission must include a valid token.
Due to statelessness of REST API, there’s no risk about such kind of CSRF attack so you can disable CSRF in your REST-based Spring application to avoid overhead on the server. Also, disabling CSRF prevention is a must for your REST APIs to function properly.
With Spring Security version 5.x or earlier, you can disable CSRF in your security configuration class as follows:
@Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/uri").authenticated() .anyRequest().permitAll() ... .and() .csrf().disable(); } }
And the following code example shows you how to disable CSRF with Spring Security 6.x or later in the security configuration class:
@Configuration public class SecurityConfig { @Bean SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests( auth -> auth.requestMatchers("/uri").authenticated() .anyRequest().permitAll() ).csrf(csrf -> csrf.disable()); return http.build(); } }
Note that when CSRF is disabled, the CsrfFilter is removed from Spring Security filter chain. And if you disable CSRF for testing purpose, remember enable it back to avoid security risks. Check the following video to see disabling CSRF in a real Spring project:
Related Spring Security Articles:
Learn more about Spring Security:
- Spring Security Registration and Login Tutorial
- Spring Security Role-based Authorization Tutorial
- Spring Security Remember Me Examples
- Spring Security Forgot Password Tutorial
- Spring Security Social Login with Google and Facebook
- Full Spring Security Tutorials List
Comments