Allow CORS configuration using config properties
Prior to this commit, a Spring GraphQL application would need to implement `WebMvcConfigurer` or `WebFluxConfigurer` to register a specific CORS configuration and map it to the GraphQL endpoint. This commit adds new configuration properties under the `spring.graphql.cors.*` namespace that helps configuring CORS for the GraphQL endpoint. Closes gh-26
This commit is contained in:
@@ -0,0 +1,154 @@
|
||||
/*
|
||||
* Copyright 2020-2021 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.graphql.boot;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.context.properties.PropertyMapper;
|
||||
import org.springframework.boot.convert.DurationUnit;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
|
||||
/**
|
||||
* Configuration properties for GraphQL endpoint's CORS support.
|
||||
*
|
||||
* @author Andy Wilkinson
|
||||
* @author Brian Clozel
|
||||
* @since 1.0.0
|
||||
*/
|
||||
@ConfigurationProperties(prefix = "spring.graphql.cors")
|
||||
public class GraphQlCorsProperties {
|
||||
/**
|
||||
* Comma-separated list of origins to allow. '*' allows all origins. When credentials
|
||||
* are allowed, '*' cannot be used and origin patterns should be configured instead.
|
||||
* When no allowed origins or allowed origin patterns are set, CORS support is
|
||||
* disabled.
|
||||
*/
|
||||
private List<String> allowedOrigins = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Comma-separated list of origin patterns to allow. Unlike allowed origins which only
|
||||
* supports '*', origin patterns are more flexible (for example
|
||||
* 'https://*.example.com') and can be used when credentials are allowed. When no
|
||||
* allowed origin patterns or allowed origins are set, CORS support is disabled.
|
||||
*/
|
||||
private List<String> allowedOriginPatterns = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Comma-separated list of methods to allow. '*' allows all methods. When not set,
|
||||
* defaults to GET.
|
||||
*/
|
||||
private List<String> allowedMethods = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Comma-separated list of headers to allow in a request. '*' allows all headers.
|
||||
*/
|
||||
private List<String> allowedHeaders = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Comma-separated list of headers to include in a response.
|
||||
*/
|
||||
private List<String> exposedHeaders = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Whether credentials are supported. When not set, credentials are not supported.
|
||||
*/
|
||||
private Boolean allowCredentials;
|
||||
|
||||
/**
|
||||
* How long the response from a pre-flight request can be cached by clients. If a
|
||||
* duration suffix is not specified, seconds will be used.
|
||||
*/
|
||||
@DurationUnit(ChronoUnit.SECONDS)
|
||||
private Duration maxAge = Duration.ofSeconds(1800);
|
||||
|
||||
public List<String> getAllowedOrigins() {
|
||||
return this.allowedOrigins;
|
||||
}
|
||||
|
||||
public void setAllowedOrigins(List<String> allowedOrigins) {
|
||||
this.allowedOrigins = allowedOrigins;
|
||||
}
|
||||
|
||||
public List<String> getAllowedOriginPatterns() {
|
||||
return this.allowedOriginPatterns;
|
||||
}
|
||||
|
||||
public void setAllowedOriginPatterns(List<String> allowedOriginPatterns) {
|
||||
this.allowedOriginPatterns = allowedOriginPatterns;
|
||||
}
|
||||
|
||||
public List<String> getAllowedMethods() {
|
||||
return this.allowedMethods;
|
||||
}
|
||||
|
||||
public void setAllowedMethods(List<String> allowedMethods) {
|
||||
this.allowedMethods = allowedMethods;
|
||||
}
|
||||
|
||||
public List<String> getAllowedHeaders() {
|
||||
return this.allowedHeaders;
|
||||
}
|
||||
|
||||
public void setAllowedHeaders(List<String> allowedHeaders) {
|
||||
this.allowedHeaders = allowedHeaders;
|
||||
}
|
||||
|
||||
public List<String> getExposedHeaders() {
|
||||
return this.exposedHeaders;
|
||||
}
|
||||
|
||||
public void setExposedHeaders(List<String> exposedHeaders) {
|
||||
this.exposedHeaders = exposedHeaders;
|
||||
}
|
||||
|
||||
public Boolean getAllowCredentials() {
|
||||
return this.allowCredentials;
|
||||
}
|
||||
|
||||
public void setAllowCredentials(Boolean allowCredentials) {
|
||||
this.allowCredentials = allowCredentials;
|
||||
}
|
||||
|
||||
public Duration getMaxAge() {
|
||||
return this.maxAge;
|
||||
}
|
||||
|
||||
public void setMaxAge(Duration maxAge) {
|
||||
this.maxAge = maxAge;
|
||||
}
|
||||
|
||||
public CorsConfiguration toCorsConfiguration() {
|
||||
if (CollectionUtils.isEmpty(this.allowedOrigins) && CollectionUtils.isEmpty(this.allowedOriginPatterns)) {
|
||||
return null;
|
||||
}
|
||||
PropertyMapper map = PropertyMapper.get();
|
||||
CorsConfiguration configuration = new CorsConfiguration();
|
||||
map.from(this::getAllowedOrigins).to(configuration::setAllowedOrigins);
|
||||
map.from(this::getAllowedOriginPatterns).to(configuration::setAllowedOriginPatterns);
|
||||
map.from(this::getAllowedHeaders).whenNot(CollectionUtils::isEmpty).to(configuration::setAllowedHeaders);
|
||||
map.from(this::getAllowedMethods).whenNot(CollectionUtils::isEmpty).to(configuration::setAllowedMethods);
|
||||
map.from(this::getExposedHeaders).whenNot(CollectionUtils::isEmpty).to(configuration::setExposedHeaders);
|
||||
map.from(this::getMaxAge).whenNonNull().as(Duration::getSeconds).to(configuration::setMaxAge);
|
||||
map.from(this::getAllowCredentials).whenNonNull().to(configuration::setAllowCredentials);
|
||||
return configuration;
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.io.Resource;
|
||||
@@ -47,7 +48,10 @@ import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.codec.ServerCodecConfigurer;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.reactive.HandlerMapping;
|
||||
import org.springframework.web.reactive.config.CorsRegistry;
|
||||
import org.springframework.web.reactive.config.WebFluxConfigurer;
|
||||
import org.springframework.web.reactive.function.server.RouterFunction;
|
||||
import org.springframework.web.reactive.function.server.RouterFunctions;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
@@ -69,6 +73,7 @@ import static org.springframework.web.reactive.function.server.RequestPredicates
|
||||
@ConditionalOnClass({GraphQL.class, GraphQlHttpHandler.class})
|
||||
@ConditionalOnBean(GraphQlSource.class)
|
||||
@AutoConfigureAfter(GraphQlServiceAutoConfiguration.class)
|
||||
@EnableConfigurationProperties(GraphQlCorsProperties.class)
|
||||
public class GraphQlWebFluxAutoConfiguration {
|
||||
|
||||
private static final Log logger = LogFactory.getLog(GraphQlWebFluxAutoConfiguration.class);
|
||||
@@ -147,4 +152,25 @@ public class GraphQlWebFluxAutoConfiguration {
|
||||
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public static class GraphQlEndpointCorsConfiguration implements WebFluxConfigurer {
|
||||
|
||||
final GraphQlProperties graphql;
|
||||
|
||||
final GraphQlCorsProperties cors;
|
||||
|
||||
public GraphQlEndpointCorsConfiguration(GraphQlProperties graphql, GraphQlCorsProperties cors) {
|
||||
this.graphql = graphql;
|
||||
this.cors = cors;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
CorsConfiguration configuration = cors.toCorsConfiguration();
|
||||
if (configuration != null) {
|
||||
registry.addMapping(graphql.getPath()).combine(configuration);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
|
||||
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.io.Resource;
|
||||
@@ -52,7 +53,10 @@ import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.GenericHttpMessageConverter;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.servlet.HandlerMapping;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import org.springframework.web.servlet.function.RouterFunction;
|
||||
import org.springframework.web.servlet.function.RouterFunctions;
|
||||
import org.springframework.web.servlet.function.ServerResponse;
|
||||
@@ -76,6 +80,7 @@ import static org.springframework.web.servlet.function.RequestPredicates.content
|
||||
@ConditionalOnClass({GraphQL.class, GraphQlHttpHandler.class})
|
||||
@ConditionalOnBean(GraphQlSource.class)
|
||||
@AutoConfigureAfter(GraphQlServiceAutoConfiguration.class)
|
||||
@EnableConfigurationProperties(GraphQlCorsProperties.class)
|
||||
public class GraphQlWebMvcAutoConfiguration {
|
||||
|
||||
private static final Log logger = LogFactory.getLog(GraphQlWebMvcAutoConfiguration.class);
|
||||
@@ -168,4 +173,26 @@ public class GraphQlWebMvcAutoConfiguration {
|
||||
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public static class GraphQlEndpointCorsConfiguration implements WebMvcConfigurer {
|
||||
|
||||
final GraphQlProperties graphql;
|
||||
|
||||
final GraphQlCorsProperties cors;
|
||||
|
||||
public GraphQlEndpointCorsConfiguration(GraphQlProperties graphql, GraphQlCorsProperties cors) {
|
||||
this.graphql = graphql;
|
||||
this.cors = cors;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
CorsConfiguration configuration = cors.toCorsConfiguration();
|
||||
if (configuration != null) {
|
||||
registry.addMapping(graphql.getPath()).combine(configuration);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -22,5 +22,46 @@
|
||||
"description": "Whether percentile histograms should be published.",
|
||||
"defaultValue": false
|
||||
}
|
||||
],
|
||||
"hints": [
|
||||
{
|
||||
"name": "spring.graphql.cors.allowed-headers",
|
||||
"values": [
|
||||
{
|
||||
"value": "*"
|
||||
}
|
||||
],
|
||||
"providers": [
|
||||
{
|
||||
"name": "any"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "spring.graphql.cors.allowed-methods",
|
||||
"values": [
|
||||
{
|
||||
"value": "*"
|
||||
}
|
||||
],
|
||||
"providers": [
|
||||
{
|
||||
"name": "any"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "spring.graphql.cors.allowed-origins",
|
||||
"values": [
|
||||
{
|
||||
"value": "*"
|
||||
}
|
||||
],
|
||||
"providers": [
|
||||
{
|
||||
"name": "any"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -32,6 +32,7 @@ import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.graphql.execution.RuntimeWiringConfigurer;
|
||||
import org.springframework.graphql.web.WebInterceptor;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
@@ -50,7 +51,10 @@ class GraphQlWebFluxAutoConfigurationTests {
|
||||
.withPropertyValues(
|
||||
"spring.main.web-application-type=reactive",
|
||||
"spring.graphql.schema.printer.enabled=true",
|
||||
"spring.graphql.schema.locations=classpath:books/");
|
||||
"spring.graphql.schema.locations=classpath:books/",
|
||||
"spring.graphql.cors.allowed-origins=https://example.com",
|
||||
"spring.graphql.cors.allowed-methods=POST",
|
||||
"spring.graphql.cors.allow-credentials=true");
|
||||
|
||||
@Test
|
||||
void query() {
|
||||
@@ -144,6 +148,26 @@ class GraphQlWebFluxAutoConfigurationTests {
|
||||
.value(containsString("type Book")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void corsConfiguration() {
|
||||
testWithWebClient((client) -> {
|
||||
String query = "{" +
|
||||
" bookById(id: \\\"book-1\\\"){ " +
|
||||
" id" +
|
||||
" name" +
|
||||
" pageCount" +
|
||||
" author" +
|
||||
" }" +
|
||||
"}";
|
||||
client.post().uri("").bodyValue("{ \"query\": \"" + query + "\"}")
|
||||
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")
|
||||
.header(HttpHeaders.ORIGIN, "https://example.com")
|
||||
.exchange().expectStatus().isOk()
|
||||
.expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "https://example.com")
|
||||
.expectHeader().valueEquals(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); ;
|
||||
});
|
||||
}
|
||||
|
||||
private void testWithWebClient(Consumer<WebTestClient> consumer) {
|
||||
this.contextRunner.run((context) -> {
|
||||
WebTestClient client = WebTestClient.bindToApplicationContext(context)
|
||||
|
||||
@@ -30,6 +30,7 @@ import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.graphql.execution.RuntimeWiringConfigurer;
|
||||
import org.springframework.graphql.web.WebInterceptor;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
@@ -54,7 +55,10 @@ class GraphQlWebMvcAutoConfigurationTests {
|
||||
.withPropertyValues(
|
||||
"spring.main.web-application-type=servlet",
|
||||
"spring.graphql.schema.printer.enabled=true",
|
||||
"spring.graphql.schema.locations=classpath:books/");
|
||||
"spring.graphql.schema.locations=classpath:books/",
|
||||
"spring.graphql.cors.allowed-origins=https://example.com",
|
||||
"spring.graphql.cors.allowed-methods=POST",
|
||||
"spring.graphql.cors.allow-credentials=true");
|
||||
|
||||
@Test
|
||||
void query() {
|
||||
@@ -128,6 +132,28 @@ class GraphQlWebMvcAutoConfigurationTests {
|
||||
.andExpect(content().string(Matchers.containsString("type Book"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void corsConfiguration() {
|
||||
testWith((mockMvc) -> {
|
||||
String query = "{" +
|
||||
" bookById(id: \\\"book-1\\\"){ " +
|
||||
" id" +
|
||||
" name" +
|
||||
" pageCount" +
|
||||
" author" +
|
||||
" }" +
|
||||
"}";
|
||||
MvcResult result = mockMvc.perform(post("/graphql")
|
||||
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")
|
||||
.header(HttpHeaders.ORIGIN, "https://example.com")
|
||||
.content("{\"query\": \"" + query + "\"}")).andReturn();
|
||||
mockMvc.perform(asyncDispatch(result))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().stringValues(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "https://example.com"))
|
||||
.andExpect(header().stringValues(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"));
|
||||
});
|
||||
}
|
||||
|
||||
private void testWith(MockMvcConsumer mockMvcConsumer) {
|
||||
this.contextRunner.run((context) -> {
|
||||
MediaType mediaType = MediaType.APPLICATION_JSON;
|
||||
|
||||
@@ -16,5 +16,7 @@
|
||||
:github-issues: https://github.com/{github-repo}/issues/
|
||||
:github-main-branch: https://github.com/{github-repo}/tree/main
|
||||
:github-wiki: https://github.com/{github-repo}/wiki
|
||||
:javadoc: https://docs.spring.io/spring-graphql/docs/{spring-graphql-version}/api
|
||||
:spring-framework-ref-docs: https://docs.spring.io/spring-framework/docs/current/reference/html
|
||||
:spring-boot-version: current
|
||||
:spring-boot-ref-docs: https://docs.spring.io/spring-boot/docs/{spring-boot-version}/reference/html
|
||||
@@ -232,6 +232,29 @@ spring.graphql.graphiql.path=/graphiql
|
||||
----
|
||||
|
||||
|
||||
[[boot-graphql-cors]]
|
||||
== CORS configuration
|
||||
|
||||
Spring web frameworks all support CORS (Cross-Origin Resource Sharing), which is a critical part
|
||||
of your web configuration if your GraphQL API is meant to be accessed by browsers using different domains.
|
||||
|
||||
You can configure CORS support with properties:
|
||||
|
||||
[source,properties,indent=0,subs="verbatim"]
|
||||
----
|
||||
spring.graphql.cors.allowed-origins=https://example.org # Comma-separated list of origins to allow. '*' allows all origins.
|
||||
spring.graphql.cors.allowed-origin-patterns= # Comma-separated list of origin patterns like 'https://*.example.com' to allow.
|
||||
spring.graphql.cors.allowed-methods=GET,POST # Comma-separated list of methods to allow. '*' allows all methods.
|
||||
spring.graphql.cors.allowed-headers= # Comma-separated list of headers to allow in a request. '*' allows all headers.
|
||||
spring.graphql.cors.exposed-headers= # Comma-separated list of headers to include in a response.
|
||||
spring.graphql.cors.allow-credentials= # Whether credentials are supported. When not set, credentials are not supported.
|
||||
spring.graphql.cors.max-age=1800s # How long the response from a pre-flight request can be cached by clients.
|
||||
----
|
||||
|
||||
TIP: For more information about the properties and their meaning, check out the {javadoc}/org/springframework/graphql/boot/GraphQlCorsProperties.html[GraphQlCorsProperties Javadoc].
|
||||
|
||||
You can also learn more about CORS and Spring support in {spring-framework-ref-docs}/web.html#mvc-cors[Spring MVC] and
|
||||
{spring-framework-ref-docs}/web-reactive.html#webflux-cors[Spring WebFlux].
|
||||
|
||||
[[boot-graphql-metrics]]
|
||||
== Metrics
|
||||
|
||||
Reference in New Issue
Block a user