DATAREST-573 - Add support for new CORS configuration mechanisms introduced in Spring 4.2.

We now support CORS configuration mechanisms introduced in Spring 4.2. CORS can be configured on multiple levels: Repository interface, Repository REST controller and global level. Spring Data REST CORS configuration is isolated so Spring Web MVC'S CORS configuration does not apply to Spring Data REST resources.

 Multiple configuration sources are merged so different aspects of CORS can be configured in separate locations.

@CrossOrigin
interface PersonRepository extends CrudRepository<Person, Long> {}

@RepositoryRestController
@RequestMapping("/person")
public class PersonController {

	@CrossOrigin(maxAge = 3600)
	@RequestMapping(method = RequestMethod.GET, "/xml/{id}", produces = MediaType.APPLICATION_XML_VALUE)
	public Person retrieve(@PathVariable Long id) {
		// ...
	}
}

@Component
public class SpringDataRestCustomization extends RepositoryRestConfigurerAdapter {

  @Override
  public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {

    config.addCorsMapping("/person/**")
        .allowedOrigins("http://domain2.com")
        .allowedMethods("PUT", "DELETE")
        .allowedHeaders("header1", "header2", "header3")
        .exposedHeaders("header1", "header2")
        .allowCredentials(false).maxAge(3600);
  }
}
This commit is contained in:
Mark Paluch
2016-10-10 16:45:42 +02:00
committed by Oliver Gierke
parent 19aa41926a
commit a3870ca528
11 changed files with 698 additions and 10 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2016 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.
@@ -15,6 +15,7 @@
*/
package org.springframework.data.rest.webmvc;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
@@ -23,15 +24,24 @@ import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.data.repository.support.Repositories;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.core.mapping.ResourceMappings;
import org.springframework.data.rest.core.mapping.ResourceMetadata;
import org.springframework.data.rest.webmvc.support.JpaHelper;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.util.StringValueResolver;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.ProducesRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
@@ -45,6 +55,7 @@ import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandl
*
* @author Jon Brisbin
* @author Oliver Gierke
* @author Mark Paluch
*/
public class RepositoryRestHandlerMapping extends BasePathAwareHandlerMapping {
@@ -53,7 +64,9 @@ public class RepositoryRestHandlerMapping extends BasePathAwareHandlerMapping {
private final ResourceMappings mappings;
private final RepositoryRestConfiguration configuration;
private final Repositories repositories;
private StringValueResolver embeddedValueResolver;
private JpaHelper jpaHelper;
/**
@@ -64,6 +77,19 @@ public class RepositoryRestHandlerMapping extends BasePathAwareHandlerMapping {
* @param config must not be {@literal null}.
*/
public RepositoryRestHandlerMapping(ResourceMappings mappings, RepositoryRestConfiguration config) {
this(mappings, config, null);
}
/**
* Creates a new {@link RepositoryRestHandlerMapping} for the given {@link ResourceMappings}
* {@link RepositoryRestConfiguration} and {@link Repositories}.
*
* @param mappings must not be {@literal null}.
* @param config must not be {@literal null}.
* @param repositories can be {@literal null} if {@link CrossOrigin} resolution is not required.
*/
public RepositoryRestHandlerMapping(ResourceMappings mappings, RepositoryRestConfiguration config,
Repositories repositories) {
super(config);
@@ -72,6 +98,7 @@ public class RepositoryRestHandlerMapping extends BasePathAwareHandlerMapping {
this.mappings = mappings;
this.configuration = config;
this.repositories = repositories;
}
/**
@@ -81,7 +108,17 @@ public class RepositoryRestHandlerMapping extends BasePathAwareHandlerMapping {
this.jpaHelper = jpaHelper;
}
/*
/* (non-Javadoc)
* @see org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#setEmbeddedValueResolver(org.springframework.util.StringValueResolver)
*/
@Override
public void setEmbeddedValueResolver(StringValueResolver resolver) {
embeddedValueResolver = resolver;
super.setEmbeddedValueResolver(resolver);
}
/*
* (non-Javadoc)
* @see org.springframework.web.servlet.handler.AbstractHandlerMethodMapping#lookupHandlerMethod(java.lang.String, javax.servlet.http.HttpServletRequest)
*/
@@ -155,6 +192,32 @@ public class RepositoryRestHandlerMapping extends BasePathAwareHandlerMapping {
return new ProducesRequestCondition(mediaTypes.toArray(new String[mediaTypes.size()]));
}
/* (non-Javadoc)
* @see org.springframework.web.servlet.handler.AbstractHandlerMethodMapping#getCorsConfiguration(java.lang.Object, javax.servlet.http.HttpServletRequest)
*/
@Override
protected CorsConfiguration getCorsConfiguration(Object handler, HttpServletRequest request) {
CorsConfiguration corsConfiguration = super.getCorsConfiguration(handler, request);
String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
String repositoryLookupPath = new BaseUri(configuration.getBaseUri()).getRepositoryLookupPath(lookupPath);
if (!StringUtils.hasText(repositoryLookupPath) || repositories == null) {
return corsConfiguration;
}
// Repository root resource
CorsConfiguration repositoryConfiguration = new CorsConfigurationAccessor(mappings, repositories,
embeddedValueResolver).findCorsConfiguration(lookupPath);
if (repositoryConfiguration != null) {
return corsConfiguration != null ? corsConfiguration.combine(repositoryConfiguration) : repositoryConfiguration;
}
return corsConfiguration;
}
/**
* Returns the first segment of the given repository lookup path.
*
@@ -166,4 +229,140 @@ public class RepositoryRestHandlerMapping extends BasePathAwareHandlerMapping {
int secondSlashIndex = repositoryLookupPath.indexOf('/', repositoryLookupPath.startsWith("/") ? 1 : 0);
return secondSlashIndex == -1 ? repositoryLookupPath : repositoryLookupPath.substring(0, secondSlashIndex);
}
/**
* Accessor to obtain {@link CorsConfiguration} for exposed repositories.
* <p>
* Exported Repository classes can be annotated with {@link CrossOrigin} to configure CORS for a specific repository.
*
* @author Mark Paluch
* @since 2.6
*/
static class CorsConfigurationAccessor {
private final ResourceMappings mappings;
private final Repositories repositories;
private final StringValueResolver embeddedValueResolver;
/**
* Creates a new {@link CorsConfigurationAccessor} given {@link ResourceMappings}, {@link Repositories} and
* {@link StringValueResolver}.
*
* @param mappings must not be {@literal null}.
* @param repositories must not be {@literal null}.
* @param embeddedValueResolver may be {@literal null} if not present.
*/
CorsConfigurationAccessor(ResourceMappings mappings, Repositories repositories,
StringValueResolver embeddedValueResolver) {
Assert.notNull(mappings, "ResourceMappings must not be null!");
Assert.notNull(repositories, "Repositories must not be null!");
this.mappings = mappings;
this.repositories = repositories;
this.embeddedValueResolver = embeddedValueResolver;
}
CorsConfiguration findCorsConfiguration(String lookupPath) {
ResourceMetadata resource = getResourceMetadata(getRepositoryBasePath(lookupPath));
return resource != null ? createConfiguration(
repositories.getRepositoryInformationFor(resource.getDomainType()).getRepositoryInterface()) : null;
}
private ResourceMetadata getResourceMetadata(String basePath) {
if (mappings.exportsTopLevelResourceFor(basePath)) {
for (ResourceMetadata metadata : mappings) {
if (metadata.getPath().matches(basePath) && metadata.isExported()) {
return metadata;
}
}
}
return null;
}
/**
* Creates {@link CorsConfiguration} from a repository interface.
*
* @param repositoryInterface the repository interface
* @return {@link CorsConfiguration} or {@literal null}.
*/
protected CorsConfiguration createConfiguration(Class<?> repositoryInterface) {
CrossOrigin typeAnnotation = AnnotatedElementUtils.findMergedAnnotation(repositoryInterface, CrossOrigin.class);
if (typeAnnotation == null) {
return null;
}
CorsConfiguration config = new CorsConfiguration();
updateCorsConfig(config, typeAnnotation);
if (CollectionUtils.isEmpty(config.getAllowedOrigins())) {
config.setAllowedOrigins(Arrays.asList(CrossOrigin.DEFAULT_ORIGINS));
}
if (CollectionUtils.isEmpty(config.getAllowedMethods())) {
for (HttpMethod httpMethod : HttpMethod.values()) {
config.addAllowedMethod(httpMethod);
}
}
if (CollectionUtils.isEmpty(config.getAllowedHeaders())) {
config.setAllowedHeaders(Arrays.asList(CrossOrigin.DEFAULT_ALLOWED_HEADERS));
}
if (config.getAllowCredentials() == null) {
config.setAllowCredentials(CrossOrigin.DEFAULT_ALLOW_CREDENTIALS);
}
if (config.getMaxAge() == null) {
config.setMaxAge(CrossOrigin.DEFAULT_MAX_AGE);
}
return config;
}
private void updateCorsConfig(CorsConfiguration config, CrossOrigin annotation) {
for (String origin : annotation.origins()) {
config.addAllowedOrigin(resolveCorsAnnotationValue(origin));
}
for (RequestMethod method : annotation.methods()) {
config.addAllowedMethod(method.name());
}
for (String header : annotation.allowedHeaders()) {
config.addAllowedHeader(resolveCorsAnnotationValue(header));
}
for (String header : annotation.exposedHeaders()) {
config.addExposedHeader(resolveCorsAnnotationValue(header));
}
String allowCredentials = resolveCorsAnnotationValue(annotation.allowCredentials());
if ("true".equalsIgnoreCase(allowCredentials)) {
config.setAllowCredentials(true);
} else if ("false".equalsIgnoreCase(allowCredentials)) {
config.setAllowCredentials(false);
} else if (!allowCredentials.isEmpty()) {
throw new IllegalStateException("@CrossOrigin's allowCredentials value must be \"true\", \"false\", "
+ "or an empty string (\"\"): current value is [" + allowCredentials + "]");
}
if (annotation.maxAge() >= 0 && config.getMaxAge() == null) {
config.setMaxAge(annotation.maxAge());
}
}
private String resolveCorsAnnotationValue(String value) {
return (this.embeddedValueResolver != null ? this.embeddedValueResolver.resolveStringValue(value) : value);
}
}
}

View File

@@ -21,6 +21,7 @@ import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.BeanCreationException;
@@ -139,9 +140,11 @@ import org.springframework.plugin.core.OrderAwarePluginRegistry;
import org.springframework.plugin.core.PluginRegistry;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
@@ -570,6 +573,16 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon
return handlerAdapter;
}
/**
* {@link HttpRequestHandlerAdapter} to handle CORS preflight requests.
*
* @return
*/
@Bean
public HttpRequestHandlerAdapter httpRequestHandlerAdapter() {
return new HttpRequestHandlerAdapter();
}
/**
* The {@link HandlerMapping} to delegate requests to Spring Data REST controllers. Sets up a
* {@link DelegatingHandlerMapping} to make sure manually implemented {@link BasePathAwareController} instances that
@@ -582,13 +595,18 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon
@Bean
public DelegatingHandlerMapping restHandlerMapping() {
RepositoryRestHandlerMapping repositoryMapping = new RepositoryRestHandlerMapping(resourceMappings(), config());
Map<String, CorsConfiguration> corsConfigurations = config().getCorsRegistry().getCorsConfigurations();
RepositoryRestHandlerMapping repositoryMapping = new RepositoryRestHandlerMapping(resourceMappings(), config(),
repositories());
repositoryMapping.setJpaHelper(jpaHelper());
repositoryMapping.setApplicationContext(applicationContext);
repositoryMapping.setCorsConfigurations(corsConfigurations);
repositoryMapping.afterPropertiesSet();
BasePathAwareHandlerMapping basePathMapping = new BasePathAwareHandlerMapping(config());
basePathMapping.setApplicationContext(applicationContext);
basePathMapping.setCorsConfigurations(corsConfigurations);
basePathMapping.afterPropertiesSet();
List<HandlerMapping> mappings = new ArrayList<HandlerMapping>();
@@ -980,4 +998,5 @@ public class RepositoryRestMvcConfiguration extends HateoasAwareSpringDataWebCon
*/
@Deprecated
protected void configureJacksonObjectMapper(ObjectMapper objectMapper) {}
}

View File

@@ -0,0 +1,96 @@
/*
* Copyright 2016 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
*
* http://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.data.rest.webmvc;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.data.repository.support.Repositories;
import org.springframework.data.rest.core.mapping.ResourceMappings;
import org.springframework.data.rest.webmvc.RepositoryRestHandlerMapping.CorsConfigurationAccessor;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.cors.CorsConfiguration;
/**
* Unit tests for {@link CorsConfigurationAccessor}.
*
* @author Mark Paluch
* @soundtrack Aso Mamiko - Drive Me Crazy (Club Mix)
*/
@RunWith(MockitoJUnitRunner.class)
public class CorsConfigurationAccessorUnitTests {
CorsConfigurationAccessor accessor;
@Mock ResourceMappings mappings;
@Mock Repositories repositories;
@Before
public void before() throws Exception {
accessor = new CorsConfigurationAccessor(mappings, repositories, null);
}
/**
* @see DATAREST-573
*/
@Test
public void createConfigurationShouldConstructCorsConfiguration() {
CorsConfiguration configuration = accessor.createConfiguration(AnnotatedRepository.class);
assertThat(configuration, is(notNullValue()));
assertThat(configuration.getAllowCredentials(), is(true));
assertThat(configuration.getAllowedHeaders(), hasItem("*"));
assertThat(configuration.getAllowedOrigins(), hasItem("*"));
assertThat(configuration.getAllowedMethods(),
hasItems("OPTIONS", "HEAD", "GET", "PATCH", "POST", "PUT", "DELETE", "TRACE"));
assertThat(configuration.getMaxAge(), is(1800L));
}
/**
* @see DATAREST-573
*/
@Test
public void createConfigurationShouldConstructFullCorsConfiguration() {
CorsConfiguration configuration = accessor.createConfiguration(FullyConfiguredCorsRepository.class);
assertThat(configuration, is(notNullValue()));
assertThat(configuration.getAllowCredentials(), is(true));
assertThat(configuration.getAllowedHeaders(), hasItem("Content-type"));
assertThat(configuration.getExposedHeaders(), hasItem("Accept"));
assertThat(configuration.getAllowedOrigins(), hasItem("http://far.far.away"));
assertThat(configuration.getAllowedMethods(), hasItem("PATCH"));
assertThat(configuration.getAllowedMethods(), not(hasItem("DELETE")));
assertThat(configuration.getAllowCredentials(), is(true));
assertThat(configuration.getMaxAge(), is(1234L));
}
interface PlainRepository {}
@CrossOrigin
interface AnnotatedRepository {}
@CrossOrigin(origins = "http://far.far.away", allowedHeaders = "Content-type", maxAge = 1234,
exposedHeaders = "Accept", methods = RequestMethod.PATCH, allowCredentials = "true")
interface FullyConfiguredCorsRepository {}
}