33

我正在使用带有 Java 配置的 Spring-Security 3.2.0.RC2。我设置了一个简单的 HttpSecurity 配置,要求在 /v1/** 上进行基本身份验证。GET 请求有效,但 POST 请求失败,原因如下:

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

我的安全配置如下所示:

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

}

非常感谢您对此的任何帮助。

4

2 回答 2

54

CSRF保护在 Java 配置中默认启用。要禁用它:

@Configuration
public class RestSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            ...;
    }
}
于 2013-12-16T10:08:46.570 回答
6

您还可以仅对某些请求或方法禁用 CSRF 检查,对对象使用如下配置http

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

你可以在这里看到更多:

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

于 2014-09-30T18:39:17.780 回答