Polish reactive CORS support

This commit is contained in:
Rossen Stoyanchev
2016-10-10 16:37:34 -04:00
parent e31a2f778b
commit 33c48e7a17
20 changed files with 488 additions and 464 deletions

View File

@@ -15,7 +15,6 @@
*/
package org.springframework.web.reactive.handler;
import java.net.URISyntaxException;
import java.util.Collections;
import static org.junit.Assert.*;
@@ -23,9 +22,6 @@ import static org.junit.Assert.assertSame;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
@@ -44,132 +40,111 @@ import org.springframework.web.server.session.WebSessionManager;
* @author Sebastien Deleuze
* @author Rossen Stoyanchev
*/
public class CorsAbstractUrlHandlerMappingTests {
public class CorsUrlHandlerMappingTests {
private AnnotationConfigApplicationContext wac;
private AbstractUrlHandlerMapping handlerMapping;
private TestUrlHandlerMapping handlerMapping;
private Object welcomeController = new Object();
private Object mainController;
private CorsAwareHandler corsController = new CorsAwareHandler();
private CorsAwareHandler corsConfigurationSourceController;
@Before
public void setup() {
wac = new AnnotationConfigApplicationContext();
wac.register(WebConfig.class);
wac.refresh();
handlerMapping = (TestUrlHandlerMapping) wac.getBean("handlerMapping");
mainController = wac.getBean("mainController");
corsConfigurationSourceController = (CorsAwareHandler) wac.getBean("corsConfigurationSourceController");
this.handlerMapping = new AbstractUrlHandlerMapping() {};
this.handlerMapping.setUseTrailingSlashMatch(true);
this.handlerMapping.registerHandler("/welcome.html", this.welcomeController);
this.handlerMapping.registerHandler("/cors.html", this.corsController);
}
@Test
public void actualRequestWithoutCorsConfigurationProvider() throws Exception {
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/welcome.html", "http://domain2.com", "GET");
Object actual = handlerMapping.getHandler(exchange).block();
String origin = "http://domain2.com";
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/welcome.html", origin, "GET");
Object actual = this.handlerMapping.getHandler(exchange).block();
assertNotNull(actual);
assertSame(mainController, actual);
assertSame(this.welcomeController, actual);
}
@Test
public void preflightRequestWithoutCorsConfigurationProvider() throws Exception {
ServerWebExchange exchange = createExchange(HttpMethod.OPTIONS, "/welcome.html", "http://domain2.com", "GET");
Object actual = handlerMapping.getHandler(exchange).block();
String origin = "http://domain2.com";
ServerWebExchange exchange = createExchange(HttpMethod.OPTIONS, "/welcome.html", origin, "GET");
Object actual = this.handlerMapping.getHandler(exchange).block();
assertNotNull(actual);
assertEquals("NoOpHandler", actual.getClass().getSimpleName());
assertNotSame(this.welcomeController, actual);
assertNull(exchange.getResponse().getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void actualRequestWithCorsConfigurationProvider() throws Exception {
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/cors.html", "http://domain2.com", "GET");
Object actual = handlerMapping.getHandler(exchange).block();
public void actualRequestWithCorsAwareHandler() throws Exception {
String origin = "http://domain2.com";
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/cors.html", origin, "GET");
Object actual = this.handlerMapping.getHandler(exchange).block();
assertNotNull(actual);
assertSame(corsConfigurationSourceController, actual);
CorsConfiguration config = ((CorsConfigurationSource)actual).getCorsConfiguration(createExchange(HttpMethod.GET, "", "",""));
assertNotNull(config);
assertArrayEquals(config.getAllowedOrigins().toArray(), new String[]{"*"});
assertSame(this.corsController, actual);
assertEquals("*", exchange.getResponse().getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void preflightRequestWithCorsConfigurationProvider() throws Exception {
ServerWebExchange exchange = createExchange(HttpMethod.OPTIONS, "/cors.html", "http://domain2.com", "GET");
Object actual = handlerMapping.getHandler(exchange).block();
public void preFlightWithCorsAwareHandler() throws Exception {
String origin = "http://domain2.com";
ServerWebExchange exchange = createExchange(HttpMethod.OPTIONS, "/cors.html", origin, "GET");
Object actual = this.handlerMapping.getHandler(exchange).block();
assertNotNull(actual);
assertEquals("NoOpHandler", actual.getClass().getSimpleName());
assertNotSame(this.corsController, actual);
assertEquals("*", exchange.getResponse().getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void actualRequestWithMappedCorsConfiguration() throws Exception {
public void actualRequestWithGlobalCorsConfig() throws Exception {
CorsConfiguration mappedConfig = new CorsConfiguration();
mappedConfig.addAllowedOrigin("*");
this.handlerMapping.setCorsConfigurations(Collections.singletonMap("/welcome.html", mappedConfig));
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/welcome.html", "http://domain2.com", "GET");
Object actual = handlerMapping.getHandler(exchange).block();
String origin = "http://domain2.com";
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/welcome.html", origin, "GET");
Object actual = this.handlerMapping.getHandler(exchange).block();
assertNotNull(actual);
assertSame(mainController, actual);
assertSame(this.welcomeController, actual);
assertEquals("*", exchange.getResponse().getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void preflightRequestWithMappedCorsConfiguration() throws Exception {
public void preFlightRequestWithGlobalCorsConfig() throws Exception {
CorsConfiguration mappedConfig = new CorsConfiguration();
mappedConfig.addAllowedOrigin("*");
this.handlerMapping.setCorsConfigurations(Collections.singletonMap("/welcome.html", mappedConfig));
ServerWebExchange exchange = createExchange(HttpMethod.OPTIONS, "/welcome.html", "http://domain2.com", "GET");
Object actual = handlerMapping.getHandler(exchange).block();
String origin = "http://domain2.com";
ServerWebExchange exchange = createExchange(HttpMethod.OPTIONS, "/welcome.html", origin, "GET");
Object actual = this.handlerMapping.getHandler(exchange).block();
assertNotNull(actual);
assertEquals("NoOpHandler", actual.getClass().getSimpleName());
assertNotSame(this.welcomeController, actual);
assertEquals("*", exchange.getResponse().getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
private ServerWebExchange createExchange(HttpMethod method, String path, String origin,
String accessControlRequestMethod) throws URISyntaxException {
String accessControlRequestMethod) {
ServerHttpRequest request = new MockServerHttpRequest(method, "http://localhost" + path);
request.getHeaders().add(HttpHeaders.ORIGIN, origin);
request.getHeaders().add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, accessControlRequestMethod);
MockServerHttpResponse response = new MockServerHttpResponse();
WebSessionManager sessionManager = new MockWebSessionManager();
return new DefaultServerWebExchange(request, new MockServerHttpResponse(), sessionManager);
return new DefaultServerWebExchange(request, response, sessionManager);
}
@Configuration
static class WebConfig {
@Bean @SuppressWarnings("unused")
public TestUrlHandlerMapping handlerMapping() {
TestUrlHandlerMapping hm = new TestUrlHandlerMapping();
hm.setUseTrailingSlashMatch(true);
hm.registerHandler("/welcome.html", mainController());
hm.registerHandler("/cors.html", corsConfigurationSourceController());
return hm;
}
@Bean
public Object mainController() {
return new Object();
}
@Bean
public CorsAwareHandler corsConfigurationSourceController() {
return new CorsAwareHandler();
}
}
static class TestUrlHandlerMapping extends AbstractUrlHandlerMapping {
}
static class CorsAwareHandler implements CorsConfigurationSource {
private class CorsAwareHandler implements CorsConfigurationSource {
@Override
public CorsConfiguration getCorsConfiguration(ServerWebExchange exchange) {

View File

@@ -16,9 +16,13 @@
package org.springframework.web.reactive.result.method.annotation;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
@@ -30,20 +34,24 @@ import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
import org.springframework.web.server.handler.ResponseStatusExceptionHandler;
import static org.springframework.http.RequestEntity.get;
import static org.springframework.http.RequestEntity.options;
import static org.springframework.http.RequestEntity.post;
/**
* Base class for integration tests with {@code @RequestMapping methods}.
*
* @author Rossen Stoyanchev
*/
public abstract class AbstractRequestMappingIntegrationTests extends AbstractHttpHandlerIntegrationTests {
private ApplicationContext applicationContext;
private RestTemplate restTemplate = new RestTemplate();
private ApplicationContext applicationContext;
@Override
protected HttpHandler createHttpHandler() {
this.restTemplate = initRestTemplate();
this.applicationContext = initApplicationContext();
return WebHttpHandlerBuilder
.webHandler(new DispatcherHandler(this.applicationContext))
@@ -53,49 +61,98 @@ public abstract class AbstractRequestMappingIntegrationTests extends AbstractHtt
protected abstract ApplicationContext initApplicationContext();
protected RestTemplate initRestTemplate() {
return new RestTemplate();
}
ApplicationContext getApplicationContext() {
protected ApplicationContext getApplicationContext() {
return this.applicationContext;
}
RestTemplate getRestTemplate() {
protected RestTemplate getRestTemplate() {
return this.restTemplate;
}
<T> ResponseEntity<T> performGet(String url, MediaType out,
Class<T> type) throws Exception {
return this.restTemplate.exchange(prepareGet(url, out), type);
<T> ResponseEntity<T> performGet(String url, MediaType out, Class<T> type) throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(out));
return getRestTemplate().exchange(prepareGet(url, headers), type);
}
<T> ResponseEntity<T> performGet(String url, MediaType out,
ParameterizedTypeReference<T> type) throws Exception {
<T> ResponseEntity<T> performGet(String url, HttpHeaders headers, Class<T> type) throws Exception {
return getRestTemplate().exchange(prepareGet(url, headers), type);
}
return this.restTemplate.exchange(prepareGet(url, out), type);
<T> ResponseEntity<T> performGet(String url, MediaType out, ParameterizedTypeReference<T> type)
throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(out));
return this.restTemplate.exchange(prepareGet(url, headers), type);
}
<T> ResponseEntity<T> performOptions(String url, HttpHeaders headers, Class<T> type)
throws Exception {
return getRestTemplate().exchange(prepareOptions(url, headers), type);
}
<T> ResponseEntity<T> performPost(String url, MediaType in, Object body, MediaType out, Class<T> type)
throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(in);
if (out != null) {
headers.setAccept(Collections.singletonList(out));
}
return getRestTemplate().exchange(preparePost(url, headers, body), type);
}
<T> ResponseEntity<T> performPost(String url, HttpHeaders headers, Object body,
Class<T> type) throws Exception {
return getRestTemplate().exchange(preparePost(url, headers, body), type);
}
<T> ResponseEntity<T> performPost(String url, MediaType in, Object body, MediaType out,
Class<T> type) throws Exception {
ParameterizedTypeReference<T> type) throws Exception {
return this.restTemplate.exchange(preparePost(url, in, body, out), type);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(in);
if (out != null) {
headers.setAccept(Collections.singletonList(out));
}
return getRestTemplate().exchange(preparePost(url, headers, body), type);
}
<T> ResponseEntity<T> performPost(String url, MediaType in, Object body,
MediaType out, ParameterizedTypeReference<T> type) throws Exception {
return this.restTemplate.exchange(preparePost(url, in, body, out), type);
}
private RequestEntity<Void> prepareGet(String url, MediaType accept) throws Exception {
private RequestEntity<Void> prepareGet(String url, HttpHeaders headers) throws Exception {
URI uri = new URI("http://localhost:" + this.port + url);
return (accept != null ? get(uri).accept(accept).build() : get(uri).build());
RequestEntity.HeadersBuilder<?> builder = get(uri);
addHeaders(builder, headers);
return builder.build();
}
private RequestEntity<?> preparePost(String url, MediaType in, Object body, MediaType out) throws Exception {
private RequestEntity<Void> prepareOptions(String url, HttpHeaders headers) throws Exception {
URI uri = new URI("http://localhost:" + this.port + url);
return (out != null ?
RequestEntity.post(uri).contentType(in).accept(out).body(body) :
RequestEntity.post(uri).contentType(in).body(body));
RequestEntity.HeadersBuilder<?> builder = options(uri);
addHeaders(builder, headers);
return builder.build();
}
private void addHeaders(RequestEntity.HeadersBuilder<?> builder, HttpHeaders headers) {
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
for (String value : entry.getValue()) {
builder.header(entry.getKey(), value);
}
}
}
private RequestEntity<?> preparePost(String url, HttpHeaders headers, Object body) throws Exception {
URI uri = new URI("http://localhost:" + this.port + url);
RequestEntity.BodyBuilder builder = post(uri);
addHeaders(builder, headers);
return builder.body(body);
}
}

View File

@@ -18,8 +18,7 @@ package org.springframework.web.reactive.result.method.annotation;
import java.util.Properties;
import static org.junit.Assert.*;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
@@ -28,76 +27,82 @@ import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.config.WebReactiveConfiguration;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/**
* Integration tests with {@code @CrossOrigin} and {@code @RequestMapping}
* annotated handler methods.
*
* @author Sebastien Deleuze
* @author Rossen Stoyanchev
*/
public class CrossOriginAnnotationIntegrationTests extends AbstractRequestMappingIntegrationTests {
// JDK default HTTP client blacklist headers like Origin
private RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
private HttpHeaders headers;
@Before
public void setup() throws Exception {
super.setup();
this.headers = new HttpHeaders();
this.headers.setOrigin("http://site1.com");
}
@Override
protected ApplicationContext initApplicationContext() {
AnnotationConfigApplicationContext wac = new AnnotationConfigApplicationContext();
wac.register(WebConfig.class);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(WebConfig.class);
Properties props = new Properties();
props.setProperty("myOrigin", "http://site1.com");
wac.getEnvironment().getPropertySources().addFirst(new PropertiesPropertySource("ps", props));
wac.register(PropertySourcesPlaceholderConfigurer.class);
wac.refresh();
return wac;
context.getEnvironment().getPropertySources().addFirst(new PropertiesPropertySource("ps", props));
context.register(PropertySourcesPlaceholderConfigurer.class);
context.refresh();
return context;
}
@Override
RestTemplate getRestTemplate() {
return this.restTemplate;
protected RestTemplate initRestTemplate() {
// JDK default HTTP client blacklist headers like Origin
return new RestTemplate(new HttpComponentsClientHttpRequestFactory());
}
@Test
public void actualGetRequestWithoutAnnotation() {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ORIGIN, "http://site1.com");
HttpEntity<?> requestEntity = new HttpEntity(headers);
ResponseEntity<String> entity = this.restTemplate.exchange(getUrl("/no"),
HttpMethod.GET, requestEntity, String.class);
public void actualGetRequestWithoutAnnotation() throws Exception {
ResponseEntity<String> entity = performGet("/no", this.headers, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertNull(entity.getHeaders().getAccessControlAllowOrigin());
assertEquals("no", entity.getBody());
}
@Test
public void actualPostRequestWithoutAnnotation() {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ORIGIN, "http://site1.com");
HttpEntity<?> requestEntity = new HttpEntity(headers);
ResponseEntity<String> entity = this.restTemplate.exchange(getUrl("/no"),
HttpMethod.POST, requestEntity, String.class);
public void actualPostRequestWithoutAnnotation() throws Exception {
ResponseEntity<String> entity = performPost("/no", this.headers, null, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertNull(entity.getHeaders().getAccessControlAllowOrigin());
assertEquals("no-post", entity.getBody());
}
@Test
public void actualRequestWithDefaultAnnotation() {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ORIGIN, "http://site1.com");
HttpEntity<?> requestEntity = new HttpEntity(headers);
ResponseEntity<String> entity = this.restTemplate.exchange(getUrl("/default"),
HttpMethod.GET, requestEntity, String.class);
public void actualRequestWithDefaultAnnotation() throws Exception {
ResponseEntity<String> entity = performGet("/default", this.headers, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("http://site1.com", entity.getHeaders().getAccessControlAllowOrigin());
assertEquals(true, entity.getHeaders().getAccessControlAllowCredentials());
@@ -105,13 +110,9 @@ public class CrossOriginAnnotationIntegrationTests extends AbstractRequestMappin
}
@Test
public void preflightRequestWithDefaultAnnotation() {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ORIGIN, "http://site1.com");
headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
HttpEntity<?> requestEntity = new HttpEntity(headers);
ResponseEntity<Void> entity = this.restTemplate.exchange(getUrl("/default"),
HttpMethod.OPTIONS, requestEntity, Void.class);
public void preflightRequestWithDefaultAnnotation() throws Exception {
this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
ResponseEntity<Void> entity = performOptions("/default", this.headers, Void.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("http://site1.com", entity.getHeaders().getAccessControlAllowOrigin());
assertEquals(1800, entity.getHeaders().getAccessControlMaxAge());
@@ -119,23 +120,17 @@ public class CrossOriginAnnotationIntegrationTests extends AbstractRequestMappin
}
@Test
public void actualRequestWithDefaultAnnotationAndNoOrigin() {
public void actualRequestWithDefaultAnnotationAndNoOrigin() throws Exception {
HttpHeaders headers = new HttpHeaders();
HttpEntity<?> requestEntity = new HttpEntity(headers);
ResponseEntity<String> entity = this.restTemplate.exchange(getUrl("/default"),
HttpMethod.GET, requestEntity, String.class);
ResponseEntity<String> entity = performGet("/default", headers, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertNull(entity.getHeaders().getAccessControlAllowOrigin());
assertEquals("default", entity.getBody());
}
@Test
public void actualRequestWithCustomizedAnnotation() {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ORIGIN, "http://site1.com");
HttpEntity<?> requestEntity = new HttpEntity(headers);
ResponseEntity<String> entity = this.restTemplate.exchange(getUrl("/customized"),
HttpMethod.GET, requestEntity, String.class);
public void actualRequestWithCustomizedAnnotation() throws Exception {
ResponseEntity<String> entity = performGet("/customized", this.headers, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("http://site1.com", entity.getHeaders().getAccessControlAllowOrigin());
assertEquals(false, entity.getHeaders().getAccessControlAllowCredentials());
@@ -144,67 +139,54 @@ public class CrossOriginAnnotationIntegrationTests extends AbstractRequestMappin
}
@Test
public void preflightRequestWithCustomizedAnnotation() {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ORIGIN, "http://site1.com");
headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "header1, header2");
HttpEntity<?> requestEntity = new HttpEntity(headers);
ResponseEntity<String> entity = this.restTemplate.exchange(getUrl("/customized"),
HttpMethod.OPTIONS, requestEntity, String.class);
public void preflightRequestWithCustomizedAnnotation() throws Exception {
this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "header1, header2");
ResponseEntity<String> entity = performOptions("/customized", this.headers, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("http://site1.com", entity.getHeaders().getAccessControlAllowOrigin());
assertArrayEquals(new HttpMethod[] {HttpMethod.GET}, entity.getHeaders().getAccessControlAllowMethods().toArray());
assertArrayEquals(new HttpMethod[] {HttpMethod.GET},
entity.getHeaders().getAccessControlAllowMethods().toArray());
assertArrayEquals(new String[] {"header1", "header2"},
entity.getHeaders().getAccessControlAllowHeaders().toArray());
assertArrayEquals(new String[] {"header3", "header4"},
entity.getHeaders().getAccessControlExposeHeaders().toArray());
assertEquals(false, entity.getHeaders().getAccessControlAllowCredentials());
assertArrayEquals(new String[] {"header1", "header2"}, entity.getHeaders().getAccessControlAllowHeaders().toArray());
assertArrayEquals(new String[] {"header3", "header4"}, entity.getHeaders().getAccessControlExposeHeaders().toArray());
assertEquals(123, entity.getHeaders().getAccessControlMaxAge());
}
@Test
public void customOriginDefinedViaValueAttribute() {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ORIGIN, "http://site1.com");
HttpEntity<?> requestEntity = new HttpEntity(headers);
ResponseEntity<String> entity = this.restTemplate.exchange(getUrl("/origin-value-attribute"),
HttpMethod.GET, requestEntity, String.class);
public void customOriginDefinedViaValueAttribute() throws Exception {
ResponseEntity<String> entity = performGet("/origin-value-attribute", this.headers, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("http://site1.com", entity.getHeaders().getAccessControlAllowOrigin());
assertEquals("value-attribute", entity.getBody());
}
@Test
public void customOriginDefinedViaPlaceholder() {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ORIGIN, "http://site1.com");
HttpEntity<?> requestEntity = new HttpEntity(headers);
ResponseEntity<String> entity = this.restTemplate.exchange(getUrl("/origin-placeholder"),
HttpMethod.GET, requestEntity, String.class);
public void customOriginDefinedViaPlaceholder() throws Exception {
ResponseEntity<String> entity = performGet("/origin-placeholder", this.headers, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("http://site1.com", entity.getHeaders().getAccessControlAllowOrigin());
assertEquals("placeholder", entity.getBody());
}
@Test
public void classLevel() {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ORIGIN, "http://site1.com");
HttpEntity<?> requestEntity = new HttpEntity(headers);
ResponseEntity<String> entity = this.restTemplate.exchange(getUrl("/foo"),
HttpMethod.GET, requestEntity, String.class);
public void classLevel() throws Exception {
ResponseEntity<String> entity = performGet("/foo", this.headers, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("*", entity.getHeaders().getAccessControlAllowOrigin());
assertEquals(false, entity.getHeaders().getAccessControlAllowCredentials());
assertEquals("foo", entity.getBody());
entity = this.restTemplate.exchange(getUrl("/bar"), HttpMethod.GET, requestEntity, String.class);
entity = performGet("/bar", this.headers, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("*", entity.getHeaders().getAccessControlAllowOrigin());
assertEquals(false, entity.getHeaders().getAccessControlAllowCredentials());
assertEquals("bar", entity.getBody());
entity = this.restTemplate.exchange(getUrl("/baz"), HttpMethod.GET, requestEntity, String.class);
entity = performGet("/baz", this.headers, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("http://site1.com", entity.getHeaders().getAccessControlAllowOrigin());
assertEquals(true, entity.getHeaders().getAccessControlAllowCredentials());
@@ -213,107 +195,104 @@ public class CrossOriginAnnotationIntegrationTests extends AbstractRequestMappin
@Test
public void ambiguousHeaderPreflightRequest() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ORIGIN, "http://site1.com");
headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "header1");
HttpEntity<?> requestEntity = new HttpEntity(headers);
ResponseEntity<String> entity = this.restTemplate.exchange(getUrl("/ambiguous-header"),
HttpMethod.OPTIONS, requestEntity, String.class);
this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "header1");
ResponseEntity<String> entity = performOptions("/ambiguous-header", this.headers, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("http://site1.com", entity.getHeaders().getAccessControlAllowOrigin());
assertArrayEquals(new HttpMethod[] {HttpMethod.GET}, entity.getHeaders().getAccessControlAllowMethods().toArray());
assertArrayEquals(new HttpMethod[] {HttpMethod.GET},
entity.getHeaders().getAccessControlAllowMethods().toArray());
assertArrayEquals(new String[] {"header1"},
entity.getHeaders().getAccessControlAllowHeaders().toArray());
assertEquals(true, entity.getHeaders().getAccessControlAllowCredentials());
assertArrayEquals(new String[] {"header1"}, entity.getHeaders().getAccessControlAllowHeaders().toArray());
}
@Test
public void ambiguousProducesPreflightRequest() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ORIGIN, "http://site1.com");
headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
HttpEntity<?> requestEntity = new HttpEntity(headers);
ResponseEntity<String> entity = this.restTemplate.exchange(getUrl("/ambiguous-produces"),
HttpMethod.OPTIONS, requestEntity, String.class);
this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
ResponseEntity<String> entity = performOptions("/ambiguous-produces", this.headers, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("http://site1.com", entity.getHeaders().getAccessControlAllowOrigin());
assertArrayEquals(new HttpMethod[] {HttpMethod.GET}, entity.getHeaders().getAccessControlAllowMethods().toArray());
assertArrayEquals(new HttpMethod[] {HttpMethod.GET},
entity.getHeaders().getAccessControlAllowMethods().toArray());
assertEquals(true, entity.getHeaders().getAccessControlAllowCredentials());
}
private String getUrl(String path) {
return "http://localhost:" + this.port + path;
}
@Configuration
@ComponentScan(resourcePattern = "**/CrossOriginAnnotationIntegrationTests*")
@SuppressWarnings({"unused", "WeakerAccess"})
static class WebConfig extends WebReactiveConfiguration {
}
@RestController
@RestController @SuppressWarnings("unused")
private static class MethodLevelController {
@RequestMapping(path = "/no", method = RequestMethod.GET)
@GetMapping("/no")
public String noAnnotation() {
return "no";
}
@RequestMapping(path = "/no", method = RequestMethod.POST)
@PostMapping("/no")
public String noAnnotationPost() {
return "no-post";
}
@CrossOrigin
@RequestMapping(path = "/default", method = RequestMethod.GET)
@GetMapping("/default")
public String defaultAnnotation() {
return "default";
}
@CrossOrigin
@RequestMapping(path = "/default", method = RequestMethod.GET, params = "q")
@GetMapping(path = "/default", params = "q")
public void defaultAnnotationWithParams() {
}
@CrossOrigin
@RequestMapping(path = "/ambiguous-header", method = RequestMethod.GET, headers = "header1=a")
@GetMapping(path = "/ambiguous-header", headers = "header1=a")
public void ambigousHeader1a() {
}
@CrossOrigin
@RequestMapping(path = "/ambiguous-header", method = RequestMethod.GET, headers = "header1=b")
@GetMapping(path = "/ambiguous-header", headers = "header1=b")
public void ambigousHeader1b() {
}
@CrossOrigin
@RequestMapping(path = "/ambiguous-produces", method = RequestMethod.GET, produces = "application/xml")
@GetMapping(path = "/ambiguous-produces", produces = "application/xml")
public String ambigousProducesXml() {
return "<a></a>";
}
@CrossOrigin
@RequestMapping(path = "/ambiguous-produces", method = RequestMethod.GET, produces = "application/json")
@GetMapping(path = "/ambiguous-produces", produces = "application/json")
public String ambigousProducesJson() {
return "{}";
}
@CrossOrigin(origins = { "http://site1.com", "http://site2.com" }, allowedHeaders = { "header1", "header2" },
exposedHeaders = { "header3", "header4" }, methods = RequestMethod.GET, maxAge = 123, allowCredentials = "false")
@CrossOrigin(
origins = { "http://site1.com", "http://site2.com" },
allowedHeaders = { "header1", "header2" },
exposedHeaders = { "header3", "header4" },
methods = RequestMethod.GET,
maxAge = 123,
allowCredentials = "false")
@RequestMapping(path = "/customized", method = { RequestMethod.GET, RequestMethod.POST })
public String customized() {
return "customized";
}
@CrossOrigin("http://site1.com")
@RequestMapping("/origin-value-attribute")
@GetMapping("/origin-value-attribute")
public String customOriginDefinedViaValueAttribute() {
return "value-attribute";
}
@CrossOrigin("${myOrigin}")
@RequestMapping("/origin-placeholder")
@GetMapping("/origin-placeholder")
public String customOriginDefinedViaPlaceholder() {
return "placeholder";
}
@@ -321,25 +300,25 @@ public class CrossOriginAnnotationIntegrationTests extends AbstractRequestMappin
@RestController
@CrossOrigin(allowCredentials = "false")
@SuppressWarnings("unused")
private static class ClassLevelController {
@RequestMapping(path = "/foo", method = RequestMethod.GET)
@GetMapping("/foo")
public String foo() {
return "foo";
}
@CrossOrigin
@RequestMapping(path = "/bar", method = RequestMethod.GET)
@GetMapping("/bar")
public String bar() {
return "bar";
}
@CrossOrigin(allowCredentials = "true")
@RequestMapping(path = "/baz", method = RequestMethod.GET)
@GetMapping("/baz")
public String baz() {
return "baz";
}
}
}

View File

@@ -16,16 +16,14 @@
package org.springframework.web.reactive.result.method.annotation;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
@@ -36,34 +34,49 @@ import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.config.CorsRegistry;
import org.springframework.web.reactive.config.WebReactiveConfiguration;
/**
* @author Sebastien Deleuze
*/
public class CorsConfigurationIntegrationTests extends AbstractRequestMappingIntegrationTests {
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
/**
*
* Integration tests with {@code @RequestMapping} handler methods and global
* CORS configuration.
*
* @author Sebastien Deleuze
* @author Rossen Stoyanchev
*/
public class GlobalCorsConfigIntegrationTests extends AbstractRequestMappingIntegrationTests {
private HttpHeaders headers;
@Before
public void setup() throws Exception {
super.setup();
this.headers = new HttpHeaders();
this.headers.setOrigin("http://localhost:9000");
}
// JDK default HTTP client blacklist headers like Origin
private RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
@Override
protected ApplicationContext initApplicationContext() {
AnnotationConfigApplicationContext wac = new AnnotationConfigApplicationContext();
wac.register(WebConfig.class);
wac.refresh();
return wac;
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(WebConfig.class);
context.refresh();
return context;
}
@Override
RestTemplate getRestTemplate() {
return this.restTemplate;
protected RestTemplate initRestTemplate() {
// JDK default HTTP client blacklists headers like Origin
return new RestTemplate(new HttpComponentsClientHttpRequestFactory());
}
@Test
public void actualRequestWithCorsEnabled() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ORIGIN, "http://localhost:9000");
HttpEntity<?> requestEntity = new HttpEntity(headers);
ResponseEntity<String> entity = this.restTemplate.exchange(getUrl("/cors"),
HttpMethod.GET, requestEntity, String.class);
ResponseEntity<String> entity = performGet("/cors", this.headers, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("http://localhost:9000", entity.getHeaders().getAccessControlAllowOrigin());
assertEquals("cors", entity.getBody());
@@ -71,85 +84,58 @@ public class CorsConfigurationIntegrationTests extends AbstractRequestMappingInt
@Test
public void actualRequestWithCorsRejected() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ORIGIN, "http://localhost:9000");
HttpEntity<?> requestEntity = new HttpEntity(headers);
try {
this.restTemplate.exchange(getUrl("/cors-restricted"), HttpMethod.GET,
requestEntity, String.class);
performGet("/cors-restricted", this.headers, String.class);
fail();
}
catch (HttpClientErrorException e) {
assertEquals(HttpStatus.FORBIDDEN, e.getStatusCode());
return;
}
fail();
}
@Test
public void actualRequestWithoutCorsEnabled() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ORIGIN, "http://localhost:9000");
HttpEntity<?> requestEntity = new HttpEntity(headers);
ResponseEntity<String> entity = this.restTemplate.exchange(getUrl("/welcome"),
HttpMethod.GET, requestEntity, String.class);
ResponseEntity<String> entity = performGet("/welcome", this.headers, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertNull(entity.getHeaders().getAccessControlAllowOrigin());
assertEquals("welcome", entity.getBody());
}
@Test
public void preflightRequestWithCorsEnabled() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ORIGIN, "http://localhost:9000");
headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
HttpEntity<?> requestEntity = new HttpEntity(headers);
ResponseEntity<String> entity = this.restTemplate.exchange(getUrl("/cors"),
HttpMethod.OPTIONS, requestEntity, String.class);
public void preFlightRequestWithCorsEnabled() throws Exception {
this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
ResponseEntity<String> entity = performOptions("/cors", this.headers, String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("http://localhost:9000", entity.getHeaders().getAccessControlAllowOrigin());
}
@Test
public void preflightRequestWithCorsRejected() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ORIGIN, "http://localhost:9000");
headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
HttpEntity<?> requestEntity = new HttpEntity(headers);
public void preFlightRequestWithCorsRejected() throws Exception {
try {
this.restTemplate.exchange(getUrl("/cors-restricted"), HttpMethod.OPTIONS,
requestEntity, String.class);
this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
performOptions("/cors-restricted", this.headers, String.class);
fail();
}
catch (HttpClientErrorException e) {
assertEquals(HttpStatus.FORBIDDEN, e.getStatusCode());
return;
}
fail();
}
@Test
public void preflightRequestWithoutCorsEnabled() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ORIGIN, "http://localhost:9000");
headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
HttpEntity<?> requestEntity = new HttpEntity(headers);
public void preFlightRequestWithoutCorsEnabled() throws Exception {
try {
this.restTemplate.exchange(getUrl("/welcome"), HttpMethod.OPTIONS,
requestEntity, String.class);
this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
performOptions("/welcome", this.headers, String.class);
fail();
}
catch (HttpClientErrorException e) {
assertEquals(HttpStatus.FORBIDDEN, e.getStatusCode());
return;
}
fail();
}
private String getUrl(String path) {
return "http://localhost:" + this.port + path;
}
@Configuration
@ComponentScan(resourcePattern = "**/CorsConfigurationIntegrationTests*.class")
@ComponentScan(resourcePattern = "**/GlobalCorsConfigIntegrationTests*.class")
@SuppressWarnings({"unused", "WeakerAccess"})
static class WebConfig extends WebReactiveConfiguration {
@@ -160,7 +146,7 @@ public class CorsConfigurationIntegrationTests extends AbstractRequestMappingInt
}
}
@RestController
@RestController @SuppressWarnings("unused")
static class TestController {
@GetMapping("/welcome")
@@ -177,7 +163,6 @@ public class CorsConfigurationIntegrationTests extends AbstractRequestMappingInt
public String corsRestricted() {
return "corsRestricted";
}
}
}

View File

@@ -24,6 +24,7 @@ import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@@ -52,13 +53,13 @@ public class RequestMappingExceptionHandlingIntegrationTests extends AbstractReq
@Test
public void controllerThrowingException() throws Exception {
String expected = "Recovered from error: Boo";
assertEquals(expected, performGet("/thrown-exception", null, String.class).getBody());
assertEquals(expected, performGet("/thrown-exception", new HttpHeaders(), String.class).getBody());
}
@Test
public void controllerReturnsMonoError() throws Exception {
String expected = "Recovered from error: Boo";
assertEquals(expected, performGet("/mono-error", null, String.class).getBody());
assertEquals(expected, performGet("/mono-error", new HttpHeaders(), String.class).getBody());
}

View File

@@ -24,6 +24,7 @@ import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@@ -56,13 +57,13 @@ public class RequestMappingIntegrationTests extends AbstractRequestMappingIntegr
@Test
public void handleWithParam() throws Exception {
String expected = "Hello George!";
assertEquals(expected, performGet("/param?name=George", null, String.class).getBody());
assertEquals(expected, performGet("/param?name=George", new HttpHeaders(), String.class).getBody());
}
@Test
public void longStreamResult() throws Exception {
String[] expected = {"0", "1", "2", "3", "4"};
assertArrayEquals(expected, performGet("/long-stream-result", null, String[].class).getBody());
assertArrayEquals(expected, performGet("/long-stream-result", new HttpHeaders(), String[].class).getBody());
}
@Test

View File

@@ -45,6 +45,7 @@ import org.springframework.core.io.Resource;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
@@ -94,25 +95,26 @@ public class RequestMappingMessageConversionIntegrationTests extends AbstractReq
@Test
public void byteBufferResponseBodyWithFlux() throws Exception {
String expected = "Hello!";
assertEquals(expected, performGet("/raw-response/flux", null, String.class).getBody());
assertEquals(expected, performGet("/raw-response/flux", new HttpHeaders(), String.class).getBody());
}
@Test
public void byteBufferResponseBodyWithObservable() throws Exception {
String expected = "Hello!";
assertEquals(expected, performGet("/raw-response/observable", null, String.class).getBody());
assertEquals(expected, performGet("/raw-response/observable", new HttpHeaders(), String.class).getBody());
}
@Test
public void byteBufferResponseBodyWithRxJava2Observable() throws Exception {
String expected = "Hello!";
assertEquals(expected, performGet("/raw-response/rxjava2-observable", null, String.class).getBody());
assertEquals(expected, performGet("/raw-response/rxjava2-observable",
new HttpHeaders(), String.class).getBody());
}
@Test
public void byteBufferResponseBodyWithFlowable() throws Exception {
String expected = "Hello!";
assertEquals(expected, performGet("/raw-response/flowable", null, String.class).getBody());
assertEquals(expected, performGet("/raw-response/flowable", new HttpHeaders(), String.class).getBody());
}
@Test
@@ -171,7 +173,7 @@ public class RequestMappingMessageConversionIntegrationTests extends AbstractReq
@Test
public void resource() throws Exception {
ResponseEntity<byte[]> response = performGet("/resource", null, byte[].class);
ResponseEntity<byte[]> response = performGet("/resource", new HttpHeaders(), byte[].class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(response.hasBody());