Spring Cloud Gateway Cors 问题

Posted

技术标签:

【中文标题】Spring Cloud Gateway Cors 问题【英文标题】:Spring Cloud Gateway Cors issue 【发布时间】:2020-06-22 19:51:18 【问题描述】:

我在 Spring Cloud Gateway 应用程序中设置 CORS 配置时遇到问题。我设置了以下配置以允许所有内容:

spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: "*"
            allowedMethods: "*"
            allowedHeaders: "authorization"

然而,当我调用网关的端点时,我得到:

OPTIONS http://localhost:8080/api/spot/spots 403 (Forbidden)
localhost/:1 Access to XMLHttpRequest at 'http://localhost:8080/api/spot/spots' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

当我通过 UI 绕过网关调用其中一项服务时,请求正常进行。但是,我没有看到任何选项请求。

一旦我将 UI 指向网关主机,就会发生错误。

同样在“网络”选项卡中,请求显示为“失败”,没有其他信息。任何应用程序日志中也没有任何内容。 这些是响应标头:

HTTP/1.1 200 OK
transfer-encoding: chunked
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Access-Control-Allow-Origin: *
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Access-Control-Allow-Origin: *
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Date: Tue, 10 Mar 2020 21:24:11 GMT

重新启动 Item 服务(负责此端点)时,我得到 500:

timestamp: "2020-03-10T21:28:33.568+0000"
path: "/api/spot/spots"
status: 500
error: "Internal Server Error"
message: "Connection refused: localhost/127.0.0.1:49508"
requestId: "68570bc1"

它指向旧的随机端口,这意味着网关可以以某种方式连接到它。

任何想法我错过了什么?

谢谢。

该应用是开源的,可用here。 SpotController 可以找到here。 可以在 here 找到该端点的 spring-security 配置。 可以在here找到网关配置。

这里是 api 网关应用程序的日志,在调试时设置 (full logs here):

2020-03-10 22:24:10.744 DEBUG 57262 --- [ionManagerTimer] h.i.c.PoolingHttpClientConnectionManager : Closing expired connections
2020-03-10 22:24:10.812 DEBUG 57262 --- [er-item-service] c.netflix.loadbalancer.BaseLoadBalancer  : LoadBalancer:  PingTask executing [1] servers configured
2020-03-10 22:24:11.464 DEBUG 57262 --- [ctor-http-nio-2] r.n.http.server.HttpServerOperations     : [id: 0xd4a47354, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:59021] Increasing pending responses, now 1
2020-03-10 22:24:11.464 DEBUG 57262 --- [ctor-http-nio-2] reactor.netty.http.server.HttpServer     : [id: 0xd4a47354, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:59021] Handler is being applied: org.springframework.http.server.reactive.ReactorHttpHandlerAdapter@528c0cbe
2020-03-10 22:24:11.464 DEBUG 57262 --- [ctor-http-nio-2] o.s.w.s.adapter.HttpWebHandlerAdapter    : [d4a47354] HTTP OPTIONS "/api/spot/spots"
2020-03-10 22:24:11.466 DEBUG 57262 --- [ctor-http-nio-2] o.s.c.g.h.RoutePredicateHandlerMapping   : Route matched: item-service
2020-03-10 22:24:11.466 DEBUG 57262 --- [ctor-http-nio-2] o.s.c.g.h.RoutePredicateHandlerMapping   : Mapping [Exchange: OPTIONS http://localhost:8080/api/spot/spots] to Routeid='item-service', uri=lb://item-service, order=0, predicate=Paths: [/api/spot/**], match trailing slash: true, gatewayFilters=[], metadata=
2020-03-10 22:24:11.466 DEBUG 57262 --- [ctor-http-nio-2] o.s.c.g.h.RoutePredicateHandlerMapping   : [d4a47354] Mapped to org.springframework.cloud.gateway.handler.FilteringWebHandler@14780192
2020-03-10 22:24:11.467 DEBUG 57262 --- [ctor-http-nio-2] o.s.w.s.adapter.HttpWebHandlerAdapter    : [d4a47354] Completed 200 OK
2020-03-10 22:24:11.468 DEBUG 57262 --- [ctor-http-nio-2] r.n.http.server.HttpServerOperations     : [id: 0xd4a47354, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:59021] Last HTTP response frame
2020-03-10 22:24:11.468 DEBUG 57262 --- [ctor-http-nio-2] r.n.http.server.HttpServerOperations     : [id: 0xd4a47354, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:59021] No sendHeaders() called before complete, sending zero-length header
2020-03-10 22:24:11.468 DEBUG 57262 --- [ctor-http-nio-2] r.n.http.server.HttpServerOperations     : [id: 0xd4a47354, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:59021] Decreasing pending responses, now 0
2020-03-10 22:24:11.468 DEBUG 57262 --- [ctor-http-nio-2] r.n.http.server.HttpServerOperations     : [id: 0xd4a47354, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:59021] Last HTTP packet was sent, terminating the channel
2020-03-10 22:24:11.468 DEBUG 57262 --- [ctor-http-nio-2] r.n.channel.ChannelOperationsHandler     : [id: 0xd4a47354, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:59021] No ChannelOperation attached. Dropping: EmptyLastHttpContent
2020-03-10 22:24:11.486 DEBUG 57262 --- [ctor-http-nio-2] r.n.http.server.HttpServerOperations     : [id: 0xd4a47354, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:59021] Increasing pending responses, now 1
2020-03-10 22:24:11.486 DEBUG 57262 --- [ctor-http-nio-2] reactor.netty.http.server.HttpServer     : [id: 0xd4a47354, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:59021] Handler is being applied: org.springframework.http.server.reactive.ReactorHttpHandlerAdapter@528c0cbe
2020-03-10 22:24:11.486 DEBUG 57262 --- [ctor-http-nio-2] o.s.w.s.adapter.HttpWebHandlerAdapter    : [d4a47354] HTTP GET "/api/spot/spots"
2020-03-10 22:24:11.488 DEBUG 57262 --- [ctor-http-nio-2] o.s.c.g.h.RoutePredicateHandlerMapping   : Route matched: item-service
2020-03-10 22:24:11.488 DEBUG 57262 --- [ctor-http-nio-2] o.s.c.g.h.RoutePredicateHandlerMapping   : Mapping [Exchange: GET http://localhost:8080/api/spot/spots] to Routeid='item-service', uri=lb://item-service, order=0, predicate=Paths: [/api/spot/**], match trailing slash: true, gatewayFilters=[], metadata=
2020-03-10 22:24:11.488 DEBUG 57262 --- [ctor-http-nio-2] o.s.c.g.h.RoutePredicateHandlerMapping   : [d4a47354] Mapped to org.springframework.cloud.gateway.handler.FilteringWebHandler@14780192
2020-03-10 22:24:11.488 DEBUG 57262 --- [ctor-http-nio-2] o.s.c.g.handler.FilteringWebHandler      : Sorted gatewayFilterFactories: [[GatewayFilterAdapterdelegate=org.springframework.cloud.gateway.filter.RemoveCachedBodyFilter@22bf9122, order = -2147483648], [GatewayFilterAdapterdelegate=org.springframework.cloud.gateway.filter.AdaptCachedBodyGlobalFilter@69aa7d76, order = -2147482648], [GatewayFilterAdapterdelegate=org.springframework.cloud.gateway.filter.NettyWriteResponseFilter@3d88e6b9, order = -1], [GatewayFilterAdapterdelegate=org.springframework.cloud.gateway.filter.ForwardPathFilter@9687f55, order = 0], [GatewayFilterAdapterdelegate=org.springframework.cloud.gateway.filter.GatewayMetricsFilter@671d03bb, order = 0], [GatewayFilterAdapterdelegate=org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter@208205ed, order = 10000], [GatewayFilterAdapterdelegate=org.springframework.cloud.gateway.filter.LoadBalancerClientFilter@36068727, order = 10100], [GatewayFilterAdapterdelegate=org.springframework.cloud.gateway.filter.WebsocketRoutingFilter@5700c9db, order = 2147483646], [GatewayFilterAdapterdelegate=org.springframework.cloud.gateway.filter.NettyRoutingFilter@72543547, order = 2147483647], [GatewayFilterAdapterdelegate=org.springframework.cloud.gateway.filter.ForwardRoutingFilter@73afe2b7, order = 2147483647]]
2020-03-10 22:24:11.489 DEBUG 57262 --- [ctor-http-nio-2] c.n.loadbalancer.ZoneAwareLoadBalancer   : Zone aware logic disabled or there is only one zone
2020-03-10 22:24:11.490 DEBUG 57262 --- [ctor-http-nio-2] r.n.resources.PooledConnectionProvider   : [id: 0x687fa33b] Created new pooled channel, now 1 active connections and 0 inactive connections
2020-03-10 22:24:11.491 DEBUG 57262 --- [ctor-http-nio-2] reactor.netty.channel.BootstrapHandlers  : [id: 0x687fa33b] Initialized pipeline DefaultChannelPipeline(BootstrapHandlers$BootstrapInitializerHandler#0 = reactor.netty.channel.BootstrapHandlers$BootstrapInitializerHandler), (reactor.left.httpCodec = io.netty.handler.codec.http.HttpClientCodec), (reactor.right.reactiveBridge = reactor.netty.channel.ChannelOperationsHandler)
2020-03-10 22:24:11.496 DEBUG 57262 --- [ctor-http-nio-2] r.n.resources.PooledConnectionProvider   : [id: 0x687fa33b, L:/127.0.0.1:61299 - R:localhost/127.0.0.1:49508] Channel connected, now 1 active connections and 0 inactive connections
2020-03-10 22:24:11.496 DEBUG 57262 --- [ctor-http-nio-2] r.n.resources.PooledConnectionProvider   : [id: 0x687fa33b, L:/127.0.0.1:61299 - R:localhost/127.0.0.1:49508] onStateChange(PooledConnectionchannel=[id: 0x687fa33b, L:/127.0.0.1:61299 - R:localhost/127.0.0.1:49508], [connected])
2020-03-10 22:24:11.496 DEBUG 57262 --- [ctor-http-nio-2] r.n.resources.PooledConnectionProvider   : [id: 0x687fa33b, L:/127.0.0.1:61299 - R:localhost/127.0.0.1:49508] onStateChange(GETuri=/, connection=PooledConnectionchannel=[id: 0x687fa33b, L:/127.0.0.1:61299 - R:localhost/127.0.0.1:49508], [configured])
2020-03-10 22:24:11.496 DEBUG 57262 --- [ctor-http-nio-2] r.netty.http.client.HttpClientConnect    : [id: 0x687fa33b, L:/127.0.0.1:61299 - R:localhost/127.0.0.1:49508] Handler is being applied: uri=http://localhost:49508/api/spot/spots, method=GET
2020-03-10 22:24:11.497 DEBUG 57262 --- [ctor-http-nio-2] reactor.netty.channel.FluxReceive        : [id: 0xd4a47354, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:59021] Subscribing inbound receiver [pending: 0, cancelled:false, inboundDone: true]
2020-03-10 22:24:11.497 DEBUG 57262 --- [ctor-http-nio-2] r.n.resources.PooledConnectionProvider   : [id: 0x687fa33b, L:/127.0.0.1:61299 - R:localhost/127.0.0.1:49508] onStateChange(GETuri=/api/spot/spots, connection=PooledConnectionchannel=[id: 0x687fa33b, L:/127.0.0.1:61299 - R:localhost/127.0.0.1:49508], [request_sent])
2020-03-10 22:24:11.579 DEBUG 57262 --- [ctor-http-nio-2] r.n.http.client.HttpClientOperations     : [id: 0x687fa33b, L:/127.0.0.1:61299 - R:localhost/127.0.0.1:49508] Received response (auto-read:false) : [Vary=Origin, Vary=Access-Control-Request-Method, Vary=Access-Control-Request-Headers, Access-Control-Allow-Origin=*, X-Content-Type-Options=nosniff, X-XSS-Protection=1; mode=block, Cache-Control=no-cache, no-store, max-age=0, must-revalidate, Pragma=no-cache, Expires=0, X-Frame-Options=DENY, Content-Type=application/json, Transfer-Encoding=chunked, Date=Tue, 10 Mar 2020 21:24:11 GMT]
2020-03-10 22:24:11.579 DEBUG 57262 --- [ctor-http-nio-2] r.n.resources.PooledConnectionProvider   : [id: 0x687fa33b, L:/127.0.0.1:61299 - R:localhost/127.0.0.1:49508] onStateChange(GETuri=/api/spot/spots, connection=PooledConnectionchannel=[id: 0x687fa33b, L:/127.0.0.1:61299 - R:localhost/127.0.0.1:49508], [response_received])
2020-03-10 22:24:11.580 DEBUG 57262 --- [ctor-http-nio-2] reactor.netty.channel.FluxReceive        : [id: 0x687fa33b, L:/127.0.0.1:61299 - R:localhost/127.0.0.1:49508] Subscribing inbound receiver [pending: 0, cancelled:false, inboundDone: false]
2020-03-10 22:24:11.581 DEBUG 57262 --- [ctor-http-nio-2] r.n.http.client.HttpClientOperations     : [id: 0x687fa33b, L:/127.0.0.1:61299 - R:localhost/127.0.0.1:49508] Received last HTTP packet
2020-03-10 22:24:11.581 DEBUG 57262 --- [ctor-http-nio-2] o.s.w.s.adapter.HttpWebHandlerAdapter    : [d4a47354] Completed 200 OK
2020-03-10 22:24:11.581 DEBUG 57262 --- [ctor-http-nio-2] r.n.http.server.HttpServerOperations     : [id: 0xd4a47354, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:59021] Last HTTP response frame
2020-03-10 22:24:11.581 DEBUG 57262 --- [ctor-http-nio-2] r.n.http.server.HttpServerOperations     : [id: 0xd4a47354, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:59021] Decreasing pending responses, now 0
2020-03-10 22:24:11.581 DEBUG 57262 --- [ctor-http-nio-2] r.n.http.server.HttpServerOperations     : [id: 0xd4a47354, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:59021] Last HTTP packet was sent, terminating the channel
2020-03-10 22:24:11.581 DEBUG 57262 --- [ctor-http-nio-2] r.n.resources.PooledConnectionProvider   : [id: 0x687fa33b, L:/127.0.0.1:61299 - R:localhost/127.0.0.1:49508] onStateChange(GETuri=/api/spot/spots, connection=PooledConnectionchannel=[id: 0x687fa33b, L:/127.0.0.1:61299 - R:localhost/127.0.0.1:49508], [disconnecting])
2020-03-10 22:24:11.581 DEBUG 57262 --- [ctor-http-nio-2] r.n.resources.PooledConnectionProvider   : [id: 0x687fa33b, L:/127.0.0.1:61299 - R:localhost/127.0.0.1:49508] Releasing channel
2020-03-10 22:24:11.582 DEBUG 57262 --- [ctor-http-nio-2] r.n.resources.PooledConnectionProvider   : [id: 0x687fa33b, L:/127.0.0.1:61299 - R:localhost/127.0.0.1:49508] Channel cleaned, now 0 active connections and 1 inactive connections
2020-03-10 22:24:11.831 DEBUG 57262 --- [erListUpdater-1] c.n.l.DynamicServerListLoadBalancer      : List of Servers for item-service obtained from Discovery client: [localhost:49508]
2020-03-10 22:24:11.831 DEBUG 57262 --- [erListUpdater-1] c.n.l.ZoneAffinityServerListFilter       : Determining if zone affinity should be enabled with given server list: [localhost:49508]
2020-03-10 22:24:11.831 DEBUG 57262 --- [erListUpdater-1] c.n.l.ZoneAffinityServerListFilter       : zoneAffinity is overriden. blackOutServerPercentage: 0.0, activeReqeustsPerServer: 0.0, availableServers: 1
2020-03-10 22:24:11.831 DEBUG 57262 --- [erListUpdater-1] c.n.l.DynamicServerListLoadBalancer      : Filtered List of Servers for item-service obtained from Discovery client: [localhost:49508]
2020-03-10 22:24:11.831 DEBUG 57262 --- [erListUpdater-1] c.netflix.loadbalancer.BaseLoadBalancer  : LoadBalancer [item-service]: clearing server list (SET op)
2020-03-10 22:24:11.831 DEBUG 57262 --- [erListUpdater-1] c.netflix.loadbalancer.BaseLoadBalancer  : LoadBalancer [item-service]:  addServer [localhost:49508]
2020-03-10 22:24:11.831 DEBUG 57262 --- [erListUpdater-1] c.n.l.DynamicServerListLoadBalancer      : Setting server list for zones: defaultzone=[localhost:49508]
2020-03-10 22:24:11.832 DEBUG 57262 --- [erListUpdater-1] c.netflix.loadbalancer.BaseLoadBalancer  : LoadBalancer [item-service_defaultzone]: clearing server list (SET op)
2020-03-10 22:24:11.832 DEBUG 57262 --- [erListUpdater-1] c.netflix.loadbalancer.BaseLoadBalancer  : LoadBalancer [item-service_defaultzone]:  addServer [localhost:49508]
2020-03-10 22:24:11.832 DEBUG 57262 --- [erListUpdater-1] c.netflix.loadbalancer.BaseLoadBalancer  : LoadBalancer [item-service]:  forceQuickPing invoking
2020-03-10 22:24:11.832 DEBUG 57262 --- [erListUpdater-1] c.netflix.loadbalancer.BaseLoadBalancer  : LoadBalancer:  PingTask executing [1] servers configured

【问题讨论】:

好吧,看起来它是由这个“spots”端点上的`@CrossOrigin("*")`注释引起的,这导致网关cors配置出现问题。删除它似乎可以解决问题。 【参考方案1】:

配置看起来不错,但它可能没有生效。当 application.properties 和 application.yml 都在资源下时,可能会发生这种情况,我有同样的问题。

只保留一个对我有用。我的 application.properties 文件有以下 cors 设置。

spring.cloud.gateway.globalcors.add-to-simple-url-handler-mapping=true
spring.cloud.gateway.globalcors.corsConfigurations.[/**].allowedOrigins=*
spring.cloud.gateway.globalcors.corsConfigurations.[/**].allowedHeaders=*
spring.cloud.gateway.globalcors.corsConfigurations.[/**].allowedMethods=*

【讨论】:

【参考方案2】:

您是否尝试将allowedHeaders: "authorization" 更改为allowedHeaders: "*"。我遇到了同样的问题,并且只是将allowHeaders更改为通配符,因为我从客户端接收到标题x-requested-with, authorization

【讨论】:

以上是关于Spring Cloud Gateway Cors 问题的主要内容,如果未能解决你的问题,请参考以下文章

带有 Eureka 发现的 Spring Cloud Gateway 启用 CORS 策略

Angular 的 Spring Cloud Gateway Preflight Cors 错误

Gateway 过滤器,过滤器统一异常处理

spring Cloud微服务跨域问题

聊聊spring cloud gateway的NettyConfiguration

Spring Cloud实战Spring Cloud GateWay服务网关