在使用Java Config的Spring-Security中,为什么httpBasic POST需要csrf令牌?

时间:2013-12-16 02:15:07

标签: post spring-security csrf http-basic-authentication spring-java-config

我正在使用带有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();
    }
}

}

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

2 个答案:

答案 0 :(得分:54)

默认情况下,使用Java配置启用

CSRF保护。要禁用它:

@Configuration
public class RestSecurityConfig extends WebSecurityConfigurerAdapter {

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

答案 1 :(得分:5)

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

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/