借助Zuul的Spring Cloud微服务,Spring CORS筛选器问题

时间:2018-12-28 11:21:30

标签: spring spring-boot spring-security cors

给予:角度前端应用程序通过网关微服务向后端微服务发送请求。后端在Spring Cloud中。

问题::如何正确配置CORS过滤器以消除以下错误:

Access to XMLHttpRequest at 'http://gateway-service:5555/api/useful-service/myentities/' from origin 'http://localhost:4200' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:4200, http://localhost:4200', but only one is allowed.

这是我到目前为止所写的:

网关服务

我在网关服务中的主类有3个注释:@ SpringBootApplication,@ EnableZuulProxy和@Configuration。因此,由于我没有混淆任何安全性内容,因此我认为未使用Spring Security,因此我需要配置Spring MVC的CorsFilter。我就是这样(评论供将来的搜索者使用)

@Bean
public CorsFilter corsFilter() {
    CorsConfiguration corsConfig = new CorsConfiguration();
    corsConfig.setAllowCredentials(true);
    //corsConfig.addAllowedOrigin("http://localhost:4200");
    corsConfig.addAllowedOrigin("*"); //wildcard that will simply copy the value of the request's Origin header
    // into the value of the Response's Access-Control-Allow-Origin header, effectively allowing all origins.
    // You can add specific origins instead if you wish to limit them.
    corsConfig.addAllowedHeader("*");
    corsConfig.addAllowedMethod("OPTIONS");
    corsConfig.addAllowedMethod("HEAD");
    corsConfig.addAllowedMethod("GET");
    corsConfig.addAllowedMethod("POST");
    corsConfig.addAllowedMethod("PUT");
    corsConfig.addAllowedMethod("DELETE");
    corsConfig.addAllowedMethod("PATCH");
    UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
    configSource.registerCorsConfiguration("/**", corsConfig);
    return new CorsFilter(configSource);
}

有用的服务

这里的主类带有@EnableResourceServer和@SpringBootApplication注释。根据我的“业务规则”,我希望拥有Spring授权(URL安全性,以及将来的方法安全性),因此,当我配置Spring Security时,一般配置OAuth2,尤其是我也应该配置Security的cors过滤器。这是启用cors的相关安全代码段:

@Configuration
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .cors(); // by default uses a Bean by the name of corsConfigurationSource
    }
}

这就是我配置Spring Security的cors功能的方式:

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH"));
    configuration.setAllowedHeaders(Arrays.asList("X-Requested-With", "Origin", "Content-Type", "Accept", "Authorization"));
    configuration.setAllowCredentials(true);
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

不幸的是,我遇到了上面提到的错误,如果您有个解决方法,请告诉我。

1 个答案:

答案 0 :(得分:1)

似乎此问题已通过DedupeResponseHeader过滤器解决。 参见https://github.com/spring-cloud/spring-cloud-gateway/pull/866