As the WebSecurityConfigurerAdapter
uses an imperative approach you can inject the value of the security.enable-csrf
variable and disable CSRF when it be false. You are right, I think this should work out of the box.
@Configuration
public class AuthConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Value("${security.enable-csrf}")
private boolean csrfEnabled;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
if(!csrfEnabled)
{
http.csrf().disable();
}
}
}
What I did was to set that variable to false in my application.yml for when I had a dev spring profile active, although you could create a profile called nosecurity for such purposes too. It eases this process a lot:
--- application.yml ---
# Production configuration
server:
port: ${server.web.port}
admin.email: ${admin.email}
#etc
---
spring:
profiles: dev
security.enable-csrf: false
#other Development configurations
I hope it suits your needs
Update on Dec 17th of 2017
Based on a comment of a Spring Boot member this issue is fixed on new versions of Spring: I had it on version 1.5.2.RELEASE
but it seems that in version 1.5.9.RELEASE (the latest stable one to the date before version 2) its already fixed and by default csrf is disabled and it can be enabled with security.enable_csrf: true
. Therefore a possible solution could be just upgrading to version 1.5.9.RELEASE
, before making a major one to version 2 where the architecture might be quite more different.
Update on Jun 02nd of 2023
The method http.csrf
requires now a customizer of type Customizer<CsrfConfigurer<HttpSecurity>>
to configure csrf.
Therefore, instead of:
http.csrf().disable();
you should use
http.csrf(AbstractHttpConfigurer::disable);
-1.5.4
and I only added theconfigure()
method to disable the csrf. If I remove that method completely, the property is still not taken into account. The only custom security config is withconfigure(AuthenticationManagerBuilder auth)
that I use to setBCryptPasswordEncoder
. But that should not impact the csrf. – Laing@EnableWebMvc
on it that will disable auto configuration. – Tadio@SpringBootApplication
is my only annotation. And I'm extendingWebSecurityConfigurerAdapter
. Maybe that's the cause? – Laingsecurity.basic.enabled=true
and using mavenspring-boot-starter-security
. – Laing