Spring Cloud Gateway 上的 CORS 配置错误

问题描述 投票:0回答:4

请帮助。我正在使用 Spring Cloud Gateway 我一直收到这个 Cors 错误:

从来源“http://localhost:4200”访问“http://localhost:8084/users/files”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否请求的资源上存在“Access-Control-Allow-Origin”标头。

这是我的application.yml文件

  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
            allowedOrigins: "*"
            allowedMethods: "*"

这是我的路线配置:

    public RouteLocator myRoutes(RouteLocatorBuilder builder) {
        
        return builder.routes()
                .route(r -> r.path("/users/**")
                        .filters(f -> f.filter(authFilter))
                        .uri("http://localhost:8080/"))
 
                .build();
    }

这是我的 CorsConfiguration 文件。

public class CorsConfiguration {

  private static final String ALLOWED_HEADERS = "x-requested-with, authorization, Content-Type, Content-Length, Authorization, credential, X-XSRF-TOKEN";
  private static final String ALLOWED_METHODS = "GET, PUT, POST, DELETE, OPTIONS, PATCH";
  private static final String ALLOWED_ORIGIN = "*";
  private static final String MAX_AGE = "7200"; //2 hours (2 * 60 * 60) 

  @Bean
  public WebFilter corsFilter() {
    return (ServerWebExchange ctx, WebFilterChain chain) -> {
      ServerHttpRequest request = ctx.getRequest();
      if (CorsUtils.isCorsRequest(request)) {
        ServerHttpResponse response = ctx.getResponse();
        HttpHeaders headers = response.getHeaders();
        headers.add("Access-Control-Allow-Origin", ALLOWED_ORIGIN);
        headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS);
        headers.add("Access-Control-Max-Age", MAX_AGE); //OPTION how long the results of a preflight request (that is the information contained in the Access-Control-Allow-Methods and Access-Control-Allow-Headers headers) can be cached. 
        headers.add("Access-Control-Allow-Headers",ALLOWED_HEADERS);
        if (request.getMethod() == HttpMethod.OPTIONS) {
          response.setStatusCode(HttpStatus.OK);
          return Mono.empty();
        }
      }
      return chain.filter(ctx);
    };
  }

}
java spring-boot spring-cloud spring-cloud-gateway
4个回答
0
投票

你能像下面那样将 add-to-simple-url-handler-mapping 属性添加到你的 application.yml 中,然后再试一次吗

cloud:
gateway:
  globalcors:
    cors-configurations:
      '[/**]':
        allowedOrigins: "*"
        allowedMethods: "*"
    add-to-simple-url-handler-mapping: true

0
投票

在您的

CorsConfiguration
中,您仅在它是 CORS 请求时设置 CORS 标头,如果它是预检请求则不设置。预检请求失败了。所以你需要删除
if (CorsUtils.isCorsRequest(request))
条件。


0
投票

对于 maven 用户,尝试添加以下依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>

帮我解决


0
投票

使用选项“允许的来源模式:'*'”。允许所有 CORS 请求。

spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]' :
            allowed-origin-patterns: '*'
© www.soinside.com 2019 - 2024. All rights reserved.