Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import org.springframework.boot.webmvc.autoconfigure.WebMvcProperties;
import org.springframework.boot.webmvc.autoconfigure.WebMvcProperties.Apiversion;
import org.springframework.cloud.gateway.server.mvc.common.ArgumentSupplierBeanPostProcessor;
import org.springframework.cloud.gateway.server.mvc.config.GatewayCorsConfigurationSourceBuilder;
import org.springframework.cloud.gateway.server.mvc.config.GatewayMvcProperties;
import org.springframework.cloud.gateway.server.mvc.config.GatewayMvcPropertiesBeanDefinitionRegistrar;
import org.springframework.cloud.gateway.server.mvc.config.GatewayMvcRuntimeHintsProcessor;
Expand Down Expand Up @@ -74,6 +75,8 @@
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClient;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.ApiVersionConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

Expand Down Expand Up @@ -202,6 +205,14 @@ public WeightCalculatorFilter weightCalculatorFilter() {
return new WeightCalculatorFilter();
}

@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = GatewayMvcProperties.PREFIX, name = "cors.enabled", matchIfMissing = true)
public CorsFilter corsFilter(GatewayMvcProperties properties) {
CorsConfigurationSource corsConfigurationSource = GatewayCorsConfigurationSourceBuilder.build(properties);
return new CorsFilter(corsConfigurationSource);
}

@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = XForwardedRequestHeadersFilterProperties.PREFIX, name = ".enabled",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/*
* Copyright 2025-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.cloud.gateway.server.mvc.config;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.springframework.util.CollectionUtils;
import org.springframework.web.cors.CorsConfiguration;

/**
* Utility class to map Gateway route CORS metadata to Spring's {@link CorsConfiguration}.
*
* @author Fatih Celik
*/
public abstract class CorsConfigurationParser {

private static final String CORS_METADATA_KEY = "cors";

private CorsConfigurationParser() {
}

/**
* Parses the route metadata map and extracts the CORS configuration if present.
* @param metadata the metadata map associated with a route
* @return an {@link Optional} containing the mapped {@link CorsConfiguration}, or
* empty if not found
*/
@SuppressWarnings("unchecked")
public static Optional<CorsConfiguration> map(Map<String, Object> metadata) {
if (CollectionUtils.isEmpty(metadata) || !metadata.containsKey(CORS_METADATA_KEY)) {
return Optional.empty();
}

Map<String, Object> corsMetadata = (Map<String, Object>) metadata.get(CORS_METADATA_KEY);

if (CollectionUtils.isEmpty(corsMetadata)) {
return Optional.empty();
}

CorsConfiguration corsConfiguration = new CorsConfiguration();

findValue(corsMetadata, "allowCredentials")
.ifPresent(value -> corsConfiguration.setAllowCredentials((Boolean) value));
findValue(corsMetadata, "allowedHeaders")
.ifPresent(value -> corsConfiguration.setAllowedHeaders(asList(value)));
findValue(corsMetadata, "allowedMethods")
.ifPresent(value -> corsConfiguration.setAllowedMethods(asList(value)));
findValue(corsMetadata, "allowedOriginPatterns")
.ifPresent(value -> corsConfiguration.setAllowedOriginPatterns(asList(value)));
findValue(corsMetadata, "allowedOrigins")
.ifPresent(value -> corsConfiguration.setAllowedOrigins(asList(value)));
findValue(corsMetadata, "exposedHeaders")
.ifPresent(value -> corsConfiguration.setExposedHeaders(asList(value)));
findValue(corsMetadata, "maxAge").ifPresent(value -> corsConfiguration.setMaxAge(asLong(value)));

return Optional.of(corsConfiguration);
}

/**
* Extracts the first path pattern from the Path predicate if it exists. Defaults to
* "/**" if no Path predicate is found to apply CORS globally to the route.
* @param route the route properties to inspect
* @return the extracted path pattern or "/**"
*/
public static String extractPathPattern(RouteProperties route) {
if (!CollectionUtils.isEmpty(route.getPredicates())) {
for (PredicateProperties predicate : route.getPredicates()) {
if ("Path".equalsIgnoreCase(predicate.getName()) && !CollectionUtils.isEmpty(route.getPredicates())
&& !predicate.getArgs().isEmpty()) {
return predicate.getArgs().values().iterator().next();
}
}
}
return "/**";
}

/**
* Safely retrieves a value from the CORS metadata map by its key.
* @param metadata the CORS-specific metadata map
* @param key the configuration key to look up (e.g., "allowedOrigins")
* @return an {@link Optional} containing the value, or empty if the key is missing or
* null
*/
private static Optional<Object> findValue(Map<String, Object> metadata, String key) {
return Optional.ofNullable(metadata.get(key));
}

/**
* Converts a metadata configuration value into a List of Strings. Handles single
* String values and Map values.
* @param value the raw object value from the metadata map
* @return a {@link List} of string values
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private static List<String> asList(Object value) {
if (value instanceof String val) {
return List.of(val);
}
if (value instanceof Map m) {
return new ArrayList<>(m.values());
}
return (List<String>) value;
}

/**
* Converts a metadata configuration value into a Long. Handles Integer to Long
* upcasting if necessary.
* @param value the raw object value from the metadata map
* @return the numerical value represented as a Long
*/
private static Long asLong(Object value) {
if (value instanceof Integer val) {
return val.longValue();
}
return (Long) value;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* Copyright 2025-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.cloud.gateway.server.mvc.config;

import org.springframework.util.CollectionUtils;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

import static org.springframework.cloud.gateway.server.mvc.config.CorsConfigurationParser.extractPathPattern;

/**
* Builder for constructing a {@link CorsConfigurationSource} from Gateway MVC properties.
* Uses Spring 6 {@link PathPatternParser} for modern and efficient path matching.
*
* @author Fatih Celik
*/
public final class GatewayCorsConfigurationSourceBuilder {

private GatewayCorsConfigurationSourceBuilder() {
}

/**
* Builds a {@link CorsConfigurationSource} mapping route path patterns to their
* respective CORS configurations.
* @param properties the Gateway MVC properties containing route definitions
* @return a configured {@link CorsConfigurationSource}
*/
public static CorsConfigurationSource build(GatewayMvcProperties properties) {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());

if (!CollectionUtils.isEmpty(properties.getRoutes())) {
for (RouteProperties route : properties.getRoutes()) {
CorsConfigurationParser.map(route.getMetadata()).ifPresent(corsConfig -> {
String pathPattern = extractPathPattern(route);
source.registerCorsConfiguration(pathPattern, corsConfig);
});
}
}

return source;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
import org.springframework.cloud.gateway.server.mvc.predicate.PredicateAutoConfiguration;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.filter.CorsFilter;

import static org.assertj.core.api.Assertions.assertThat;

Expand Down Expand Up @@ -190,6 +191,27 @@ void loadBalancerFunctionHandlerNotAddedWhenNoLoadBalancerClientOnClasspath() {
.run(context -> assertThat(context).doesNotHaveBean("lbHandlerFunctionDefinition"));
}

@Test
void corsFilterAddedWhenPropertiesEnabled() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(FilterAutoConfiguration.class, PredicateAutoConfiguration.class,
HandlerFunctionAutoConfiguration.class, GatewayServerMvcAutoConfiguration.class,
HttpClientAutoConfiguration.class, RestTemplateAutoConfiguration.class,
RestClientAutoConfiguration.class, SslAutoConfiguration.class))
.run(context -> assertThat(context).hasSingleBean(CorsFilter.class));
}

@Test
void corsFilterNotAddedWhenPropertiesDisabled() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(FilterAutoConfiguration.class, PredicateAutoConfiguration.class,
HandlerFunctionAutoConfiguration.class, GatewayServerMvcAutoConfiguration.class,
HttpClientAutoConfiguration.class, RestTemplateAutoConfiguration.class,
RestClientAutoConfiguration.class, SslAutoConfiguration.class))
.withPropertyValues("spring.cloud.gateway.server.webmvc.cors.enabled=false")
.run(context -> assertThat(context).doesNotHaveBean(CorsFilter.class));
}

@SpringBootConfiguration
@EnableAutoConfiguration
static class TestConfig {
Expand Down
Loading