-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Add route-specific CORS configuration for MVC #4172
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
celikfatih
wants to merge
1
commit into
spring-cloud:main
Choose a base branch
from
celikfatih:feature/3302-mvc-cors-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
135 changes: 135 additions & 0 deletions
135
...ain/java/org/springframework/cloud/gateway/server/mvc/config/CorsConfigurationParser.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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()) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| && !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; | ||
| } | ||
|
|
||
| } | ||
58 changes: 58 additions & 0 deletions
58
...pringframework/cloud/gateway/server/mvc/config/GatewayCorsConfigurationSourceBuilder.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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())) { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What about routes not created via properties? |
||
| for (RouteProperties route : properties.getRoutes()) { | ||
| CorsConfigurationParser.map(route.getMetadata()).ifPresent(corsConfig -> { | ||
| String pathPattern = extractPathPattern(route); | ||
| source.registerCorsConfiguration(pathPattern, corsConfig); | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| return source; | ||
| } | ||
|
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I wonder if we want to be mindful of the filter chain order. By default this will register as
LOWEST_PRECEDENCE. If Spring Security is used it would reject any cors request before it even gets to the filter