CORS-related refinements

After this change CorsProcessor has a single processRequest method and
it also explicitly deals with a null CorsConfiguration, which for
pre-flight requests results in a rejection while for simple requests
results in no CORS headers added.

The AbstractHandlerMapping now uses a LinkedHashMap to preserve the
order in which global patterns are provided.
This commit is contained in:
Rossen Stoyanchev
2015-05-18 12:17:42 -04:00
parent 0b84f137cc
commit 5e8d838334
8 changed files with 228 additions and 195 deletions

View File

@@ -17,7 +17,7 @@
package org.springframework.web.servlet.config.annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -34,6 +34,7 @@ public class CorsConfigurer {
private final List<CorsRegistration> registrations = new ArrayList<CorsRegistration>();
/**
* Enable cross origin requests on the specified path patterns. If no path pattern is specified,
* cross-origin request handling is mapped on "/**" .
@@ -47,7 +48,7 @@ public class CorsConfigurer {
}
protected Map<String, CorsConfiguration> getCorsConfigurations() {
Map<String, CorsConfiguration> configs = new HashMap<String, CorsConfiguration>();
Map<String, CorsConfiguration> configs = new LinkedHashMap<String, CorsConfiguration>(this.registrations.size());
for (CorsRegistration registration : this.registrations) {
for (String pathPattern : registration.getPathPatterns()) {
configs.put(pathPattern, registration.getCorsConfiguration());

View File

@@ -239,7 +239,7 @@ public class WebMvcConfigurationSupport implements ApplicationContextAware, Serv
handlerMapping.setOrder(0);
handlerMapping.setInterceptors(getInterceptors());
handlerMapping.setContentNegotiationManager(mvcContentNegotiationManager());
handlerMapping.setCorsConfigurations(getCorsConfigurations());
handlerMapping.setCorsConfiguration(getCorsConfigurations());
PathMatchConfigurer configurer = getPathMatchConfigurer();
if (configurer.isUseSuffixPatternMatch() != null) {
@@ -371,7 +371,7 @@ public class WebMvcConfigurationSupport implements ApplicationContextAware, Serv
handlerMapping.setPathMatcher(mvcPathMatcher());
handlerMapping.setUrlPathHelper(mvcUrlPathHelper());
handlerMapping.setInterceptors(getInterceptors());
handlerMapping.setCorsConfigurations(getCorsConfigurations());
handlerMapping.setCorsConfiguration(getCorsConfigurations());
return handlerMapping;
}
@@ -391,7 +391,7 @@ public class WebMvcConfigurationSupport implements ApplicationContextAware, Serv
BeanNameUrlHandlerMapping mapping = new BeanNameUrlHandlerMapping();
mapping.setOrder(2);
mapping.setInterceptors(getInterceptors());
mapping.setCorsConfigurations(getCorsConfigurations());
mapping.setCorsConfiguration(getCorsConfigurations());
return mapping;
}
@@ -411,7 +411,7 @@ public class WebMvcConfigurationSupport implements ApplicationContextAware, Serv
handlerMapping.setUrlPathHelper(mvcUrlPathHelper());
handlerMapping.setInterceptors(new HandlerInterceptor[] {
new ResourceUrlProviderExposingInterceptor(mvcResourceUrlProvider())});
handlerMapping.setCorsConfigurations(getCorsConfigurations());
handlerMapping.setCorsConfiguration(getCorsConfigurations());
}
else {
handlerMapping = new EmptyHandlerMapping();

View File

@@ -20,6 +20,7 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
@@ -83,7 +84,8 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport
private CorsProcessor corsProcessor = new DefaultCorsProcessor();
private Map<String, CorsConfiguration> corsConfigurations = new HashMap<String, CorsConfiguration>();
private final Map<String, CorsConfiguration> corsConfiguration =
new LinkedHashMap<String, CorsConfiguration>();
/**
@@ -199,33 +201,41 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport
}
/**
* Configure a custom {@link CorsProcessor} to use to apply the matched
* {@link CorsConfiguration} for a request.
* <p>By default {@link DefaultCorsProcessor} is used.
* @since 4.2
*/
public void setCorsProcessor(CorsProcessor corsProcessor) {
Assert.notNull(corsProcessor, "CorsProcessor must not be null");
this.corsProcessor = corsProcessor;
}
/**
* Map the specified {@link CorsConfiguration} to the specified path.
*
* @param pathPattern the path to use. <p>Supports direct URL matches and Ant-style pattern matches.
* For syntax details, see the {@link org.springframework.util.AntPathMatcher} javadoc.
* @param config the CORS configuration to use
* @since 4.2
* Return the configured {@link CorsProcessor}.
*/
public void registerCorsConfiguration(String pathPattern, CorsConfiguration config) {
this.corsConfigurations.put(pathPattern, config);
public CorsProcessor getCorsProcessor() {
return this.corsProcessor;
}
/**
* Set the {@link CorsConfiguration} map.
*
* Set "global" CORS configuration based on URL patterns. By default the first
* matching URL pattern is combined with the CORS configuration for the
* handler, if any.
* @since 4.2
* @see #registerCorsConfiguration(String, CorsConfiguration)
*/
public void setCorsConfigurations(Map<String, CorsConfiguration> corsConfigurations) {
this.corsConfigurations = corsConfigurations;
public void setCorsConfiguration(Map<String, CorsConfiguration> corsConfiguration) {
this.corsConfiguration.clear();
if (corsConfiguration != null) {
this.corsConfiguration.putAll(corsConfiguration);
}
}
/**
* Get the CORS configuration.
*/
public Map<String, CorsConfiguration> getCorsConfiguration() {
return this.corsConfiguration;
}
/**
@@ -353,7 +363,10 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport
}
HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);
if (CorsUtils.isCorsRequest(request)) {
executionChain = getCorsHandlerExecutionChain(request, executionChain);
CorsConfiguration globalConfig = getCorsConfiguration(request);
CorsConfiguration handlerConfig = getCorsConfiguration(handler, request);
CorsConfiguration config = (globalConfig != null ? globalConfig.combine(handlerConfig) : handlerConfig);
executionChain = getCorsHandlerExecutionChain(request, executionChain, config);
}
return executionChain;
}
@@ -413,11 +426,28 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport
return chain;
}
/**
* Find the "global" CORS configuration for the given URL configured via
* {@link #setCorsConfiguration(Map)}.
* @param request the request
* @return the CORS configuration or {@code null}
*/
protected CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
for(Map.Entry<String, CorsConfiguration> entry : getCorsConfiguration().entrySet()) {
if (getPathMatcher().match(entry.getKey(), lookupPath)) {
return entry.getValue();
}
}
return null;
}
/**
* Retrieve the CORS configuration for the given handler.
* @param handler the handler to check (never {@code null}).
* @param request the current request.
* @return the CORS configuration for the handler or {@code null}.
* @since 4.2
*/
protected CorsConfiguration getCorsConfiguration(Object handler, HttpServletRequest request) {
if (handler instanceof HandlerExecutionChain) {
@@ -431,35 +461,25 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport
/**
* Update the HandlerExecutionChain for CORS-related handling.
*
* <p>For pre-flight requests, the default implementation replaces the selected
* handler with a simple HttpRequestHandler that invokes the configured
* {@link #setCorsProcessor}.
*
* <p>For actual requests, the default implementation inserts a
* HandlerInterceptor that makes CORS-related checks and adds CORS headers.
* @param request the current request
* @param chain the handler chain
* @param config the applicable CORS configuration, possibly {@code null}
* @since 4.2
*/
protected HandlerExecutionChain getCorsHandlerExecutionChain(HttpServletRequest request,
HandlerExecutionChain chain) {
CorsConfiguration globalConfig = null;
String lookupPath = this.urlPathHelper.getLookupPathForRequest(request);
for(Map.Entry<String, CorsConfiguration> entry : this.corsConfigurations.entrySet()) {
if(this.pathMatcher.match(entry.getKey(), lookupPath)) {
globalConfig = entry.getValue();
}
}
CorsConfiguration config = getCorsConfiguration(chain.getHandler(), request);
config = (globalConfig == null ? config : globalConfig.combine(config));
HandlerExecutionChain chain, CorsConfiguration config) {
if (config != null) {
if (CorsUtils.isPreFlightRequest(request)) {
HandlerInterceptor[] interceptors = chain.getInterceptors();
chain = new HandlerExecutionChain(new PreFlightHandler(config), interceptors);
}
else {
chain.addInterceptor(new CorsInterceptor(config));
}
if (CorsUtils.isPreFlightRequest(request)) {
HandlerInterceptor[] interceptors = chain.getInterceptors();
chain = new HandlerExecutionChain(new PreFlightHandler(config), interceptors);
}
else {
chain.addInterceptor(new CorsInterceptor(config));
}
return chain;
}
@@ -469,14 +489,15 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport
private final CorsConfiguration config;
public PreFlightHandler(CorsConfiguration config) {
this.config = config;
}
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
corsProcessor.processPreFlightRequest(this.config, request, response);
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws IOException {
corsProcessor.processRequest(this.config, request, response);
}
}
@@ -484,16 +505,16 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport
private final CorsConfiguration config;
public CorsInterceptor(CorsConfiguration config) {
this.config = config;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return corsProcessor.processActualRequest(this.config, request, response);
}
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
return corsProcessor.processRequest(this.config, request, response);
}
}
}

View File

@@ -16,48 +16,50 @@
package org.springframework.web.servlet.handler;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.Collections;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.support.WebContentGenerator;
/**
* Unit tests for CORS-related handling in {@link AbstractHandlerMapping}.
* @author Sebastien Deleuze
* @author Rossen Stoyanchev
*/
public class CorsAbstractHandlerMappingTests {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private AbstractHandlerMapping handlerMapping;
private StaticWebApplicationContext context;
@Before
public void setup() {
this.context = new StaticWebApplicationContext();
StaticWebApplicationContext context = new StaticWebApplicationContext();
this.handlerMapping = new TestHandlerMapping();
this.handlerMapping.setApplicationContext(this.context);
this.handlerMapping.setApplicationContext(context);
this.request = new MockHttpServletRequest();
this.request.setRemoteHost("domain1.com");
this.response = new MockHttpServletResponse();
}
@Test
@@ -67,6 +69,7 @@ public class CorsAbstractHandlerMappingTests {
this.request.addHeader(HttpHeaders.ORIGIN, "http://domain2.com/test.html");
this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
HandlerExecutionChain chain = handlerMapping.getHandler(this.request);
assertNotNull(chain);
assertTrue(chain.getHandler() instanceof SimpleHandler);
}
@@ -77,7 +80,9 @@ public class CorsAbstractHandlerMappingTests {
this.request.addHeader(HttpHeaders.ORIGIN, "http://domain2.com/test.html");
this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
HandlerExecutionChain chain = handlerMapping.getHandler(this.request);
assertTrue(chain.getHandler() instanceof SimpleHandler);
assertNotNull(chain);
assertNotNull(chain.getHandler());
assertTrue(chain.getHandler().getClass().getSimpleName().equals("PreFlightHandler"));
}
@Test
@@ -87,6 +92,7 @@ public class CorsAbstractHandlerMappingTests {
this.request.addHeader(HttpHeaders.ORIGIN, "http://domain2.com/test.html");
this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
HandlerExecutionChain chain = handlerMapping.getHandler(this.request);
assertNotNull(chain);
assertTrue(chain.getHandler() instanceof CorsAwareHandler);
CorsConfiguration config = getCorsConfiguration(chain, false);
assertNotNull(config);
@@ -100,6 +106,7 @@ public class CorsAbstractHandlerMappingTests {
this.request.addHeader(HttpHeaders.ORIGIN, "http://domain2.com/test.html");
this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
HandlerExecutionChain chain = handlerMapping.getHandler(this.request);
assertNotNull(chain);
assertNotNull(chain.getHandler());
assertTrue(chain.getHandler().getClass().getSimpleName().equals("PreFlightHandler"));
CorsConfiguration config = getCorsConfiguration(chain, true);
@@ -111,12 +118,13 @@ public class CorsAbstractHandlerMappingTests {
public void actualRequestWithMappedCorsConfiguration() throws Exception {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
this.handlerMapping.registerCorsConfiguration("/foo", config);
this.handlerMapping.setCorsConfiguration(Collections.singletonMap("/foo", config));
this.request.setMethod(RequestMethod.GET.name());
this.request.setRequestURI("/foo");
this.request.addHeader(HttpHeaders.ORIGIN, "http://domain2.com/test.html");
this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
HandlerExecutionChain chain = handlerMapping.getHandler(this.request);
assertNotNull(chain);
assertTrue(chain.getHandler() instanceof SimpleHandler);
config = getCorsConfiguration(chain, false);
assertNotNull(config);
@@ -127,12 +135,13 @@ public class CorsAbstractHandlerMappingTests {
public void preflightRequestWithMappedCorsConfiguration() throws Exception {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
this.handlerMapping.registerCorsConfiguration("/foo", config);
this.handlerMapping.setCorsConfiguration(Collections.singletonMap("/foo", config));
this.request.setMethod(RequestMethod.OPTIONS.name());
this.request.setRequestURI("/foo");
this.request.addHeader(HttpHeaders.ORIGIN, "http://domain2.com/test.html");
this.request.addHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
HandlerExecutionChain chain = handlerMapping.getHandler(this.request);
assertNotNull(chain);
assertNotNull(chain.getHandler());
assertTrue(chain.getHandler().getClass().getSimpleName().equals("PreFlightHandler"));
config = getCorsConfiguration(chain, true);