Add option to configure CORS as a route filter. (#2750)

To do so, adds 2 components:
* ApplicationLister that updates CorsProperties based on route metadata
Also:
* Renamed CorsTests to CorsGlobalTests
* Add test CorsPerRouteTests
* Add docs: split current single section into 2: global & route config
This commit is contained in:
Abel Salgado Romero
2022-10-18 19:15:15 +02:00
committed by GitHub
parent 5127bd3272
commit 074f8e9844
8 changed files with 313 additions and 4 deletions

View File

@@ -2566,8 +2566,14 @@ You can configure the logging system to have a separate access log file. The fol
====
== CORS Configuration
:cors-configuration-docs-uri: https://docs.spring.io/spring/docs/5.0.x/javadoc-api/org/springframework/web/cors/CorsConfiguration.html
You can configure the gateway to control CORS behavior. The "`global`" CORS configuration is a map of URL patterns to https://docs.spring.io/spring/docs/5.0.x/javadoc-api/org/springframework/web/cors/CorsConfiguration.html[Spring Framework `CorsConfiguration`].
You can configure the gateway to control CORS behavior globally or per route.
Both offer the same possibilities.
=== Global CORS Configuration
The "`global`" CORS configuration is a map of URL patterns to {cors-configuration-docs-uri}[Spring Framework `CorsConfiguration`].
The following example configures CORS:
.application.yml
@@ -2589,7 +2595,37 @@ spring:
In the preceding example, CORS requests are allowed from requests that originate from `docs.spring.io` for all GET requested paths.
To provide the same CORS configuration to requests that are not handled by some gateway route predicate, set the `spring.cloud.gateway.globalcors.add-to-simple-url-handler-mapping` property to `true`.
This is useful when you try to support CORS preflight requests and your route predicate does not evalute to `true` because the HTTP method is `options`.
This is useful when you try to support CORS preflight requests and your route predicate does not evaluate to `true` because the HTTP method is `options`.
=== Route CORS Configuration
The "`route`" configuration allows applying CORS directly to a route as metadata with key `cors`.
Like in the case of global configuration, the properties belong to {cors-configuration-docs-uri}[Spring Framework `CorsConfiguration`].
NOTE: If no `Path` predicate is present in the route '/**' will be applied.
.application.yml
====
[source,yaml]
----
spring:
cloud:
gateway:
routes:
- id: cors_route
uri: https://example.org
predicates:
- Path=/service/**
metadata:
cors
allowedOrigins: '*'
allowedMethods:
- GET
- POST
allowedHeaders: '*'
maxAge: 30
----
====
== Actuator API