spring-cloud-gateway icon indicating copy to clipboard operation
spring-cloud-gateway copied to clipboard

Add route-specific CORS configuration for MVC

Open celikfatih opened this issue 6 months ago • 0 comments

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 GatewayCorsConfigurationSourceBuilder to extract CORS configurations from route metadata and construct an UrlBasedCorsConfigurationSource.
  • Maintained auto-configuration cleanliness by isolating the business logic within the builder.
  • Added a robust integration test suite (CorsPerRouteMvcTests) using HttpbinTestcontainers to verify actual and pre-flight requests, including edge cases like Double CORS mitigation (using RemoveResponseHeader), 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 @author tags
  • [x] Commits are signed-off (DCO)

celikfatih avatar May 13 '26 18:05 celikfatih