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

@@ -0,0 +1,39 @@
/*
* 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.core.config;
import java.util.Map;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
/**
* Spring Data REST specific {@code CorsRegistry} implementation exposing {@link #getCorsConfigurations()}. Assists with
* the registration of {@link CorsConfiguration} mapped to a path pattern.
*
* @author Mark Paluch
* @since 2.6
*/
public class RepositoryCorsRegistry extends CorsRegistry {
/* (non-Javadoc)
* @see org.springframework.web.servlet.config.annotation.CorsRegistry#getCorsConfigurations()
*/
@Override
public Map<String, CorsConfiguration> getCorsConfigurations() {
return super.getCorsConfigurations();
}
}

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.
@@ -28,6 +28,8 @@ import org.springframework.hateoas.MediaTypes;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistration;
/**
* Spring Data REST configuration options.
@@ -36,6 +38,7 @@ import org.springframework.util.StringUtils;
* @author Oliver Gierke
* @author Jeremy Rickard
* @author Greg Turnquist
* @author Mark Paluch
*/
@SuppressWarnings("deprecation")
public class RepositoryRestConfiguration {
@@ -58,6 +61,7 @@ public class RepositoryRestConfiguration {
private ResourceMappingConfiguration repoMappings = new ResourceMappingConfiguration();
private RepositoryDetectionStrategy repositoryDetectionStrategy = RepositoryDetectionStrategies.DEFAULT;
private final RepositoryCorsRegistry corsRegistry = new RepositoryCorsRegistry();
private final ProjectionDefinitionConfiguration projectionConfiguration;
private final MetadataConfiguration metadataConfiguration;
private final EntityLookupConfiguration entityLookupConfiguration;
@@ -549,6 +553,34 @@ public class RepositoryRestConfiguration {
: repositoryDetectionStrategy;
}
/**
* Returns the {@link RepositoryCorsRegistry} to configure Cross-origin resource sharing.
*
* @return the {@link RepositoryCorsRegistry}.
* @since 2.6
* @see RepositoryCorsRegistry
* @see CorsRegistration
*/
public RepositoryCorsRegistry getCorsRegistry() {
return corsRegistry;
}
/**
* Configures Cross-origin resource sharing given a {@code path}.
*
* @param path path or path pattern, must not be {@literal null} or empty.
* @return the {@link CorsRegistration} to build a CORS configuration.
* @since 2.6
* @see CorsConfiguration
*/
public CorsRegistration addCorsMapping(String path) {
Assert.notNull(path, "Path must not be null!");
Assert.hasText(path, "Path must not be empty!");
return corsRegistry.addMapping(path);
}
/**
* Returns the {@link EntityLookupRegistrar} to create custom {@link EntityLookup} instances registered in the
* configuration.

View File

@@ -15,10 +15,12 @@
*/
package org.springframework.data.rest.core;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.springframework.data.rest.core.config.EnumTranslationConfiguration;
@@ -28,11 +30,13 @@ import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.core.domain.Profile;
import org.springframework.data.rest.core.domain.ProfileRepository;
import org.springframework.http.MediaType;
import org.springframework.web.cors.CorsConfiguration;
/**
* Unit tests for {@link RepositoryRestConfiguration}.
*
* @author Oliver Gierke
* @author Mark Paluch
* @soundtrack Adam F - Circles (Colors)
*/
public class RepositoryRestConfigurationUnitTests {
@@ -132,10 +136,25 @@ public class RepositoryRestConfigurationUnitTests {
* @see DATAREST-776
*/
@Test
public void consideresDomainTypeOfValueRepositoryLookupTypes() {
public void considersDomainTypeOfValueRepositoryLookupTypes() {
configuration.withEntityLookup().forLookupRepository(ProfileRepository.class);
assertThat(configuration.isLookupType(Profile.class), is(true));
}
/**
* @see DATAREST-573
*/
@Test
public void configuresCorsProcessing() {
configuration.addCorsMapping("/hello").maxAge(1234);
Map<String, CorsConfiguration> corsConfigurations = configuration.getCorsRegistry().getCorsConfigurations();
assertThat(corsConfigurations, hasKey("/hello"));
CorsConfiguration corsConfiguration = corsConfigurations.get("/hello");
assertThat(corsConfiguration.getMaxAge(), is(1234L));
}
}