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:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment