In Spring-Security with Java Config, why does httpBasic POST want csrf token?

shawnim picture shawnim · Dec 16, 2013 · Viewed 29.8k times · Source

I am using Spring-Security 3.2.0.RC2 with Java config. I set up a simple HttpSecurity config that asks for basic auth on /v1/**. GET requests work but POST requests fail with:

HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.

My security config looks like this:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Resource
private MyUserDetailsService userDetailsService;

@Autowired
//public void configureGlobal(AuthenticationManagerBuilder auth)
public void configure(AuthenticationManagerBuilder auth)
        throws Exception {
    StandardPasswordEncoder encoder = new StandardPasswordEncoder(); 
    auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
}

@Configuration
@Order(1)
public static class RestSecurityConfig
        extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .antMatcher("/v1/**").authorizeRequests()
                .antMatchers("/v1/**").authenticated()
            .and().httpBasic();
    }
}

}

Any help on this greatly appreciated.

Answer

holmis83 picture holmis83 · Dec 16, 2013

CSRF protection is enabled by default with Java configuration. To disable it:

@Configuration
public class RestSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            ...;
    }
}