当前位置: 首页>后端>正文

一个跨域问题分析与解决

1、背景

部署前后端应用后,测试反馈Web访问Gateway接口跨域。

2、问题

  • 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'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

    1、当前端配置withCredentials=true时, 后端配置Access-Control-Allow-Origin不能为*, 必须是相应地址。
    2、当配置withCredentials=true时, 后端需配置Access-Control-Allow-Credentials。
    3、当前端配置请求头时, 后端需要配置Access-Control-Allow-Headers为对应的请求头集合。

    前端配置axios.defaults.withCredentials=false即可。但还是建议使用默认配置true。

  • Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

    基于浏览器的同源策略,当检测发生跨域时,浏览器会向服务端发送OPTIONS请求,要求返回Access-Control-Allow-Origin、Access-Control-Allow-Methods、Access-Control-Allow-Headers、Access-Control-Allow-Credentials等属性。当请求的属性在允许的属性
    范围内,才会发送真正的请求,否则会拒绝请求。

    目前情况是GET请求正常,POST请求跨域。OPTIONS返回403。

    于是添加跨域支持的配置。

    @Bean
    public CorsWebFilter corsFilter() {

        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.setAllowCredentials(Boolean.TRUE);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }
  • The "Access-Control-Allow-Origin" header contains multiple values ",",but only one is allowed.

    配置了上面的CorsWebFilter,结果GET请求报出这个。意思是说返回了两个Access-Control-Allow-Origin *,但是只有一个是允许的。简单来说就是重复配置了。

    找了下资料,Spring Cloud Gateway版本的Bug。去Github的issue上看了看,issue挺多的,没找到。

    GET请求刚开始是正常的,后来配置了CorsWebFilter才导致跨域。容易想到Gateway默认对于GET请求的跨域支持,再配置CorsWebFilter才导致重复配置。

    去掉上面的CorsWebFilter,尝试从GlobalFilter入手,针对OPTIONS请求,响应头添加Access-Control-Allow-Origin、Access-Control-Allow-Methods、Access-Control-Allow-Headers、Access-Control-Allow-Credentials。结果发现这个OPTIONS请求没有进入GlobalFilter。

    接着尝试从WebFilter入手,代码如下:

      @Override
      public Mono<Void> filter(ServerWebExchange ctx, WebFilterChain chain) {
          ServerHttpRequest request = ctx.getRequest();
          if (!CorsUtils.isCorsRequest(request)) {
              return chain.filter(ctx);
          }
          String path = request.getPath().value();
          ServerHttpResponse response = ctx.getResponse();
          if ("/favicon.ico".equals(path)) {
              response.setStatusCode(HttpStatus.OK);
              return Mono.empty();
          }
          HttpHeaders requestHeaders = request.getHeaders();
          HttpMethod requestMethod = requestHeaders.getAccessControlRequestMethod();
          HttpHeaders headers = response.getHeaders();
          headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());
          if (requestMethod != null) {
              headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders.getAccessControlRequestHeaders().toString().replace("[", "").replace("]", ""));
              headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.name());
          }
          headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
          headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, ALL);
          headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
          if (request.getMethod() == HttpMethod.OPTIONS) {
              log.info("----CorsWebFilter into Cors Support----");
              response.setStatusCode(HttpStatus.OK);
              return Mono.empty();
          }
          return chain.filter(ctx);
      }
    

    POST请求跨域问题成功解决,但是GET请求依然报The "Access-Control-Allow-Origin" header contains multiple values ",",but only one is allowed.原因是上面代码没有过滤掉GET请求,修改如下:

      @Override
      public Mono<Void> filter(ServerWebExchange ctx, WebFilterChain chain) {
          ServerHttpRequest request = ctx.getRequest();
          if (!CorsUtils.isCorsRequest(request)) {
              return chain.filter(ctx);
          }
          String path = request.getPath().value();
          ServerHttpResponse response = ctx.getResponse();
          if ("/favicon.ico".equals(path)) {
              response.setStatusCode(HttpStatus.OK);
              return Mono.empty();
          }
          if (request.getMethod() == HttpMethod.OPTIONS) {
              log.info("----CorsWebFilter into Cors Support----");
              HttpHeaders requestHeaders = request.getHeaders();
              HttpMethod requestMethod = requestHeaders.getAccessControlRequestMethod();
              HttpHeaders headers = response.getHeaders();
              headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());
              if (requestMethod != null) {
                  headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders.getAccessControlRequestHeaders().toString().replace("[", "").replace("]", ""));
                  headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.name());
              }
              headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
              headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, ALL);
              headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
              response.setStatusCode(HttpStatus.OK);
              return Mono.empty();
          }
          return chain.filter(ctx);
      }
    

    最终,跨域问题解决。

3、总结

跨域问题场景很多,解决方式也很多。跟项目部署架构、框架都有关系,需要根据错误信息,一点点去排查。


https://www.xamrdz.com/backend/3cs1944793.html

相关文章: