Frage

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.

War es hilfreich?

Lösung

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()
            ...;
    }
}

Andere Tipps

You can also disable the CSRF check only on some requests or methods, using a configuration like the following for the http object:

http
  .csrf().requireCsrfProtectionMatcher(new RequestMatcher() {

    private Pattern allowedMethods = 
      Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");

    private RegexRequestMatcher apiMatcher = 
      new RegexRequestMatcher("/v[0-9]*/.*", null);

    @Override
    public boolean matches(HttpServletRequest request) {
        // CSRF disabled on allowedMethod
        if(allowedMethods.matcher(request.getMethod()).matches())
            return false;

        // CSRF disabled on api calls
        if(apiMatcher.matches(request))
            return false;

        // CSRF enables for other requests
        return true;
    }
});

You can see more here:

http://blog.netgloo.com/2014/09/28/spring-boot-enable-the-csrf-check-selectively-only-for-some-requests/

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top