无法在Spring中配置CSRF而不会面临CORS错误

时间:2017-06-27 00:13:28

标签: java spring spring-security cors csrf

Spring Boot's Issue #5834之后,为了设置正确的CORS并解除支持所有来源的错误,我有以下代码:

@Configuration
@EnableWebSecurity
public class SecurityAdapter extends WebSecurityConfigurerAdapter
{
    @Override
    protected void configure(HttpSecurity http)
        throws Exception
    {
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry authorizeRequests = http.authorizeRequests();

        authorizeRequests.antMatchers("/logon_check").permitAll();
        authorizeRequests.antMatchers("/logon").permitAll();
        authorizeRequests.anyRequest().authenticated();

        http
            .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
        .and()
            .cors()
        .and()
            .httpBasic()
        .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(ImmutableList.of("*"));
        configuration.setAllowedMethods(ImmutableList.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
        // setAllowCredentials(true) is important, otherwise:
        // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
        configuration.setAllowCredentials(true);
        // setAllowedHeaders is important! Without it, OPTIONS preflight request
        // will fail with 403 Invalid CORS request
        configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

}

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter
{
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
    }
}

但OPTIONS预检请求返回403:

XMLHttpRequest cannot load http://192.168.2.10:8080/logon_check. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.2.10:4200' is therefore not allowed access. The response had HTTP status code 403.

这些是请求标头:

OPTIONS /logon_check HTTP/1.1
Host: 192.168.2.10:8080
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: GET
Origin: http://192.168.2.10:4200
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36
Access-Control-Request-Headers: x-requested-with
Accept: */*
Referer: http://192.168.2.10:4200/logon
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,fa;q=0.6

响应标题:

HTTP/1.1 403
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Length: 20
Date: Mon, 26 Jun 2017 23:56:06 GMT

有人可以帮我配置Spring,所以所有的来源都通过了吗?

1 个答案:

答案 0 :(得分:0)

我找到了解决问题的方法,但我不确定这种修复方法是否是正确的做法。

在跟踪Spring的代码几个小时之后,我意识到问题在于请求中允许的HTTP头。因此,更改此行可以解决问题:

configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type", "X-Requested-With", "X-XSRF-TOKEN"));

在上面一行中,我已将"X-Requested-With", "X-XSRF-TOKEN"添加到请求所允许的标头列表中。这两个额外的标题是我需要添加的标题。可能还有一些其他情况/浏览器可能需要其他一些标头。所以一般修复可能是:

configuration.setAllowedHeaders(ImmutableList.of("*"));

但是,我不确定这是否存在安全风险。