spring-cloud-gateway
spring-cloud-gateway copied to clipboard
Add route-specific CORS configuration for MVC
Resolves gh-3302
What this PR does / why we need it: Currently, Spring Cloud Gateway MVC lacks the ability to define CORS configurations on a per-route basis via route metadata, a feature that exists in the WebFlux implementation. This PR introduces route-specific CORS configuration support for the MVC module.
How it was implemented:
- Created
GatewayCorsConfigurationSourceBuilderto extract CORS configurations from route metadata and construct anUrlBasedCorsConfigurationSource. - Maintained auto-configuration cleanliness by isolating the business logic within the builder.
- Added a robust integration test suite (
CorsPerRouteMvcTests) usingHttpbinTestcontainersto verify actual and pre-flight requests, including edge cases like Double CORS mitigation (usingRemoveResponseHeader), wildcard origins (allowedOriginPatterns), and custom headers.
Backward Compatibility:
The feature uses @ConditionalOnProperty(prefix = GatewayMvcProperties.PREFIX + ".cors", name = "enabled", matchIfMissing = true). It acts as a transparent "no-op" unless CORS metadata is explicitly defined on a route, ensuring zero disruption to existing applications while providing a global kill-switch if needed.
Checklist:
- [x] Code formatting applied (
./mvnw spring-javaformat:apply) - [x] Apache License headers added to new files
- [x] Javadoc included with
@authortags - [x] Commits are signed-off (DCO)