Spring Cloud - Zuul Proxy正在生成一个没有“访问控制-允许-起源”的ajax响应

启动应用:

@SpringBootApplication
@EnableZuulProxy
public class ZuulServer {

     public static void main(String[] args) {
         new SpringApplicationBuilder(ZuulServer.class).web(true).run(args);
     }
 }

我的 YAML 文件是这样的:

server:
   port:8080

spring:
   application:
      name: zuul

eureka:
client:
  enabled: true
    serviceUrl:
       defaultZone: http://localhost:8761/eureka/



zuul:
    proxy:
       route:
         springapp: /springapp

我有一个名为 springapp 的微服务应用程序(在端口 8081 上),并且有一些休息服务。以下是我的客户端 UI 应用:

    <html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script type="text/javascript" src="js/libs/jquery/jquery.min.js" ></script>
    </head>
    <body>
        <script type="text/javascript">
            $.ajax({
                url: 'http://localhost:8080/zuul/springapp/departments',
                type: 'GET'
            }).done(function (data) {
                consoe.log(data);
                document.write(data);
            });
        </script>        

    </body>
</html>

但我得到一个

XMLHttpRequest cannot load http://localhost:8080/zuul/springapp/departments. No
    'Access-Control-Allow-Origin' header is present on the requested
    resource. Origin 'http://localhost:8383' is therefore not allowed access.

这个UI HTML5应用程序 http://localhost:8383/SimpleAPp/index.html。CORS, CORS, CORS...请帮忙。顺便说一句,http://localhost:8080/zuul/springapp/departments 在浏览器地址栏上返回一个json列表。这里的 spring.io 博客说不需要过滤器,因为zuulproxy可以照顾它,但我不知道为什么它不适合我。


答案 1

将这段代码添加到用@EnableZuulProxy注释的类中应该可以解决问题。

@Bean
public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("OPTIONS");
    config.addAllowedMethod("HEAD");
    config.addAllowedMethod("GET");
    config.addAllowedMethod("PUT");
    config.addAllowedMethod("POST");
    config.addAllowedMethod("DELETE");
    config.addAllowedMethod("PATCH");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

答案 2

我遇到了类似的问题,Angular Web应用程序使用Spring Boot与Zuul和Spring Security实现的RESTful服务。

上述解决方案均无效。我意识到问题不在于Zuul,而在于Spring Security。

正如官方文档(CORS with Spring Security)所述,在使用Spring Security时,必须在Spring Security之前配置CORS。

最后,我能够将Grinish Nepal的解决方案(参见之前的答案)整合到一个有效的解决方案中。

事不宜迟,以下是使用Spring Security和Zuul启用CORS的代码:


    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        //irrelevant for this problem
        @Autowired
        private MyBasicAuthenticationEntryPoint authenticationEntryPoint;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    //configure CORS -- uses a Bean by the name of     corsConfigurationSource (see method below)
                    //CORS must be configured prior to Spring Security
                    .cors().and()
                    //configuring security - irrelevant for this problem
                    .authorizeRequests()
                        .anyRequest().authenticated()
                        .and()
                    .httpBasic()
                    .authenticationEntryPoint(authenticationEntryPoint);

            //irrelevant for this problem
            http.addFilterAfter(new CustomFilter(),
                    BasicAuthenticationFilter.class);
        }

        //The CORS filter bean - Configures allowed CORS any (source) to any 
        //(api route and method) endpoint
        @Bean
        CorsConfigurationSource corsConfigurationSource() {
            final UrlBasedCorsConfigurationSource source = new     UrlBasedCorsConfigurationSource();
            final CorsConfiguration config = new CorsConfiguration();
            config.setAllowCredentials(true);
            config.addAllowedOrigin(CorsConfiguration.ALL);
            config.addAllowedHeaders(Collections.singletonList(CorsConfiguration.ALL));
            config.addAllowedMethod("OPTIONS");
            config.addAllowedMethod("HEAD");
            config.addAllowedMethod("GET");
            config.addAllowedMethod("PUT");
            config.addAllowedMethod("POST");
            config.addAllowedMethod("DELETE");
            config.addAllowedMethod("PATCH");
            source.registerCorsConfiguration("/**", config);
            return source;
        }

        //configuring BA usernames and passwords - irrelevant for this problem
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws     Exception {
           ...
        }
    }

推荐