How to disable CSRF in Spring Security?

Tech Insights

1. What is a CSRF(Cross-Site Request Forgery) attack?

Cross-Site Request Forgery allows an attacker to force an end user to make calls that they do not intend to make. With the CSRF protection disabled, the attacker can easily change the values of a parameter in a valid URL and invoke it. The attacker can convince the victim to click on any link which submits the modified URL.

Any web application should have the CSRF protection enabled. It will produce an HTTP 403 access denied error in case of an attack. However, there are cases you may want to disable the CSRF protection like if you are only creating a service that is used by non-browser clients.

Before Spring Security version 4, the CSRF protection was disabled by default. Starting from Spring Security 4.x, the CSRF protection is enabled by default. That means, a CSRF token named _csrf is added to the HttpServletRequest.

2. How to disable the CSRF protection in Spring?

There are 2 ways to disable the CSRF protection in a Spring application.

2.1) Disable CSRF using Spring Security configuration code

SecurityConfig class

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	
	//--other code
	
	@Override
    protected void configure(HttpSecurity http) throws Exception {
       //--other code

       http.csrf().disable(); //to disable the CSRF protection
    }
}

2.2) Disable CSRF using application.properties file

There is no direct way to disable the CSRF protection by using the application.properties file. We configure it by using the security.enable-csrf variable.

application.properties

security.enable-csrf=false

SecurityConfig class

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	@Value("${security.enable-csrf}")
    private boolean csrfEnabled;

	//--other code
	
	@Override
    protected void configure(HttpSecurity http) throws Exception {
       //--other code
	   if(!csrfEnabled)
		  http.csrf().disable(); //to disable the CSRF protection
    }
}

Here we inject the value of the security.enable-csrf variable and disable CSRF based on its value.