17

启动应用:

@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 负责处理,但我不知道为什么它对我不起作用。

4

7 回答 7

46

将这段代码添加到使用 @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);
}
于 2016-04-07T23:44:22.320 回答
6

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

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

正如官方文档(带有 Spring Security 的 CORS)所述,使用 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 {
           ...
        }
    }
于 2017-10-17T17:01:50.653 回答
5

当您的应用程序运行时,http://localhost:8383您只能对http://localhost:8383. Zuul 没有也无法改变这一点。

Zuul 可以做的是将请求例如映射http://localhost:8383/zuul/http://localhost:8080/zuul/. 但是您的浏览器必须调用http://localhost:8383/zuul/springapp/departments并且您必须配置该映射。

于 2015-02-23T14:21:11.447 回答
4

只需将以下内容添加到对我有用的配置中

zuul:
    ignoredHeaders: Access-Control-Allow-Credentials, Access-Control-Allow-Origin
于 2020-04-23T00:53:07.507 回答
4

我有同样的问题,我已经通过添加 CorsFilter bean 来修复

  @Bean
  public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
  }

并添加zuul的属性这段代码

zuul:
  sensitiveHeaders:
  ignored-headers: Access-Control-Allow-Credentials, Access-Control-Allow-Origin

您可以在此处找到有关此问题的更多详细信息

于 2019-02-06T17:34:25.607 回答
2

那只是浏览器告诉你你违反了它的共同来源政策(见维基百科条目和互联网上的大量材料,这些都与你添加的标签无关)。您可以通过服务 CORS 飞行前检查(例如在 a 中Filter)来教导浏览器可以从不同地址加载资源,或者通过代理加载 HTML(提示:后者更容易且不易出错) .

于 2015-02-23T10:31:41.313 回答
1

对于那些即使@Bean CorsFilter添加后仍然存在问题的人,请检查控制器是否也带有注释@CrossOrigin,这种 CORS 在控制器级别和 Zuul 代理上的重复可能会导致问题。

于 2021-10-01T04:43:48.390 回答