首页 文章

使用Spring Boot和Zuul进行CORS预检请求的Host vs Origin标头

提问于
浏览
1

我正在使用Zuul与 Spring Cloud Camden SR5Spring Boot 1.4.4.RELEASE

我的前端是由 Node Express 服务器提供的 React.js 应用程序 . 我的API落后于zuul .

前端可以通过 https://test.mydomain.com 和API(Zuul)通过 https://api-test.mydomain.com 访问

Zuul 我有一个 CORS 过滤器来设置CORS标头(正确吗?):

if(corsAllowedOrigin.contains(host)){
        log.debug("{} is allowed", origin);
        response.setHeader("Access-Control-Allow-Origin", origin);
    }
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", allowHeaders);
response.setHeader("Access-Control-Expose-Headers", exposeHeaders);
chain.doFilter(req, res);

使用React.js,我使用Fetch对API进行HTTP调用 .

在每个 GETPOST 请求之前,浏览器会使用以下标头执行 OPTIONS 请求:

  • 主持人: api-test.mydomain.com

  • 原产地: https://test.mydomain.com

当我使用 Spring Cloud Brixton.SR6Spring Boot 1.3.4.RELEASE 时工作正常 .

Now however I'm getting a 403 and the error message is Invalid CORS request.

使用REST客户端我注意到如果我更改 Headers 以便 Host == Origin 然后我得到一个 200 OK

CORS spec我可以找到:

除了检查Origin标头之外,强烈建议资源作者检查Host标头 . 也就是说,确保该标头提供的主机名与资源所在的服务器的主机名匹配 . 这将提供针对DNS重新绑定攻击的保护 .

这就是我现在得到 403 的原因吗?如何在不失败 OPTIONS 请求的情况下在不同的主机上运行我的API?

更新

如果我将CORS过滤器添加到边缘服务后面的每个单独服务,我似乎可以解决问题 . 这是因为我确保每个服务都填充 Access-Control-Allow-Origin 标头 .

在更新之前,我只在我的边缘服务(Zuul)上有一个CORS过滤器,我认为这是要走的路 . 当然,如果我需要为每项服务配置CORS,这似乎很浪费?这是要走的路吗?

1 回答

  • 0

    出于某种原因,如果我使用Spring提供的CORS过滤器( org.springframework.web.filter.CorsFilter.CorsFilter ),它似乎有效:

    @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;
    }
    

相关问题