一、CORS 配置
你可以配置网关来控制全局或每个路由的 CORS 行为。两者都提供同样的可能性。
1. Global CORS 配置
“global” CORS配置是对 Spring Framework CorsConfiguration 的URL模式的映射。下面的例子配置了 CORS。
Example 77. application.yml
spring:cloud:gateway:globalcors:cors-configurations:'[/**]':allowedOrigins: "https://docs.spring.io"allowedMethods:- GET
在前面的例子中,对于所有GET请求的路径,允许来自 docs.spring.io 的请求的CORS请求。
要为未被某些网关路由谓词处理的请求提供相同的 CORS 配置,请将 spring.cloud.gateway.globalcors.add-to-simple-url-handler-mapping 属性设为 true。当你试图支持 CORS 预检请求,而你的路由谓词因为 HTTP 方法是 options 而不能评估为 true 时,这很有用。
2. 路由的 CORS 配置
“route” configuration 允许将CORS直接应用于带有key CORS 的路由作为元数据。像全局配置一样,这些属性属于 Spring Framework CorsConfiguration。
如果路由中没有 Path 谓词,则将应用 '/**'。
Example 78. application.yml
spring:cloud:gateway:routes:- id: cors_routeuri: https://example.orgpredicates:- Path=/service/**metadata:corsallowedOrigins: '*'allowedMethods:- GET- POSTallowedHeaders: '*'maxAge: 30
二、路由元数据配置
你可以通过使用元数据为每个路由配置额外的参数,如下所示。
Example 73. application.yml
spring:cloud:gateway:routes:- id: route_with_metadatauri: https://example.orgmetadata:optionName: "OptionValue"compositeObject:name: "value"iAmNumber: 1
你可以从一个 exchange 所获取所有的元数据属性,如下所示
Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
// get all metadata properties
route.getMetadata();
// get a single metadata property
route.getMetadata(someKey);
三、配置(Configuration)
Spring Cloud Gateway 的配置是由 RouteDefinitionLocator 实例的集合驱动的。下面的列表显示了 RouteDefinitionLocator 接口的定义。
Example 71. RouteDefinitionLocator.java
public interface RouteDefinitionLocator {Flux<RouteDefinition> getRouteDefinitions();
}
默认情况下,PropertiesRouteDefinitionLocator 通过使用Spring Boot的 @ConfigurationProperties 机制加载属性。
前面的配置例子都使用了一种快捷方式,即使用位置参数而不是命名参数。下面的两个例子是等价的。
Example 72. application.yml
spring:cloud:gateway:routes:- id: setstatus_routeuri: https://example.orgfilters:- name: SetStatusargs:status: 401- id: setstatusshortcut_routeuri: https://example.orgfilters:- SetStatus=401
对于网关的某些用途来说,属性已经足够了,但一些生产用例会从外部来源(如数据库)加载配置中受益。未来的里程碑版本将有基于 Spring Data Repository 的 RouteDefinitionLocator 实现,如 Redis、MongoDB和Cassandra。
四、TLS 和 SSL
网关可以通过遵循通常的 Spring server configuration 来监听 HTTPS 请求。下面的例子显示了如何做到这一点。
Example 67. application.yml
server:ssl:enabled: truekey-alias: scgkey-store-password: scg1234key-store: classpath:scg-keystore.p12key-store-type: PKCS12
你可以将网关路由到HTTP和HTTPS后端。如果你要路由到HTTPS后端,你可以通过以下配置将网关配置为信任所有下游的证书。
Example 68. application.yml
spring:cloud:gateway:httpclient:ssl:useInsecureTrustManager: true
使用不安全的 trust manager 不适合于生产。对于生产部署,你可以用一组已知的证书来配置网关,它可以通过以下配置来信任。
Example 69. application.yml
spring:cloud:gateway:httpclient:ssl:trustedX509Certificates:- cert1.pem- cert2.pem
如果 Spring Cloud Gateway 没有配置受信任的证书,就会使用默认的 trust store(你可以通过设置 javax.net.ssl.trustStore 系统属性来覆盖它)。
1. TLS 握手
网关维护着一个client pool,它用来路由到后端。当通过HTTPS进行通信时,客户端发起了一个TLS握手。一些 timeout 配置与这个握手相关。你可以对这些 timeouts 进行配置,如下(默认值)。
Example 70. application.yml
spring:cloud:gateway:httpclient:ssl:handshake-timeout-millis: 10000close-notify-flush-timeout-millis: 3000close-notify-read-timeout-millis: 0