Add CORS support

This commit introduces support for CORS in Spring Framework.

Cross-origin resource sharing (CORS) is a mechanism that allows
many resources (e.g. fonts, JavaScript, etc.) on a web page to
be requested from another domain outside the domain from which
the resource originated. It is defined by the CORS W3C
recommandation (http://www.w3.org/TR/cors/).

A new annotation @CrossOrigin allows to enable CORS support
on Controller type or method level. By default all origins
("*") are allowed.

@RestController
public class SampleController {

	@CrossOrigin
	@RequestMapping("/foo")
	public String foo() {
		// ...
	}
}

Various @CrossOrigin attributes allow to customize the CORS configuration.

@RestController
public class SampleController {

	@CrossOrigin(origin = { "http://site1.com", "http://site2.com" },
				 allowedHeaders = { "header1", "header2" },
				 exposedHeaders = { "header1", "header2" },
				 method = RequestMethod.DELETE,
				 maxAge = 123, allowCredentials = "true")
	@RequestMapping(value = "/foo", method = { RequestMethod.GET, RequestMethod.POST} )
	public String foo() {
		// ...
	}
}

A CorsConfigurationSource interface can be implemented by HTTP request
handlers that want to support CORS by providing a CorsConfiguration
that will be detected at AbstractHandlerMapping level. See for
example ResourceHttpRequestHandler that implements this interface.

Global CORS configuration should be supported through ControllerAdvice
(with type level @CrossOrigin annotated class or class implementing
CorsConfigurationSource), or with XML namespace and JavaConfig
configuration, but this is not implemented yet.

Issue: SPR-9278
This commit is contained in:
Sebastien Deleuze
2015-04-02 15:46:30 +02:00
parent 35f40ae654
commit b0e1e66b7f
24 changed files with 1942 additions and 196 deletions

View File

@@ -27,10 +27,11 @@ import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.InvalidMediaTypeException;
@@ -43,6 +44,9 @@ import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.CorsUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.sockjs.SockJsException;
import org.springframework.web.socket.sockjs.SockJsService;
@@ -60,7 +64,7 @@ import org.springframework.web.util.WebUtils;
* @author Sebastien Deleuze
* @since 4.0
*/
public abstract class AbstractSockJsService implements SockJsService {
public abstract class AbstractSockJsService implements SockJsService, CorsConfigurationSource {
private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
@@ -447,16 +451,8 @@ public abstract class AbstractSockJsService implements SockJsService {
protected abstract void handleTransportRequest(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler webSocketHandler, String sessionId, String transport) throws SockJsException;
/**
* Check the {@code Origin} header value and eventually call {@link #addCorsHeaders(ServerHttpRequest, ServerHttpResponse, HttpMethod...)}.
* If the request origin is not allowed, the request is rejected.
* @return false if the request is rejected, else true
* @since 4.1.2
*/
protected boolean checkAndAddCorsHeaders(ServerHttpRequest request, ServerHttpResponse response, HttpMethod... httpMethods) {
HttpHeaders requestHeaders = request.getHeaders();
HttpHeaders responseHeaders = response.getHeaders();
String origin = requestHeaders.getOrigin();
protected boolean checkOrigin(ServerHttpRequest request, ServerHttpResponse response, HttpMethod... httpMethods) throws IOException {
String origin = request.getHeaders().getOrigin();
if (origin == null) {
return true;
@@ -468,46 +464,26 @@ public abstract class AbstractSockJsService implements SockJsService {
return false;
}
boolean hasCorsResponseHeaders = false;
try {
// Perhaps a CORS Filter has already added this?
hasCorsResponseHeaders = !CollectionUtils.isEmpty(responseHeaders.get("Access-Control-Allow-Origin"));
}
catch (NullPointerException npe) {
// See SPR-11919 and https://issues.jboss.org/browse/WFLY-3474
}
if (!this.suppressCors && !hasCorsResponseHeaders) {
addCorsHeaders(request, response, httpMethods);
}
return true;
}
protected void addCorsHeaders(ServerHttpRequest request, ServerHttpResponse response, HttpMethod... httpMethods) {
HttpHeaders requestHeaders = request.getHeaders();
HttpHeaders responseHeaders = response.getHeaders();
responseHeaders.add("Access-Control-Allow-Origin", requestHeaders.getFirst("Origin"));
responseHeaders.add("Access-Control-Allow-Credentials", "true");
List<String> accessControllerHeaders = requestHeaders.get("Access-Control-Request-Headers");
if (accessControllerHeaders != null) {
for (String header : accessControllerHeaders) {
responseHeaders.add("Access-Control-Allow-Headers", header);
}
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
if (!this.suppressCors && CorsUtils.isCorsRequest(request)) {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.addAllowedMethod("*");
config.setAllowCredentials(true);
config.setMaxAge(ONE_YEAR);
config.addAllowedHeader("*");
return config;
}
if (!ObjectUtils.isEmpty(httpMethods)) {
responseHeaders.add("Access-Control-Allow-Methods", StringUtils.arrayToDelimitedString(httpMethods, ", "));
responseHeaders.add("Access-Control-Max-Age", String.valueOf(ONE_YEAR));
}
responseHeaders.add(HttpHeaders.VARY, HttpHeaders.ORIGIN);
return null;
}
protected void addCacheHeaders(ServerHttpResponse response) {
response.getHeaders().setCacheControl("public, max-age=" + ONE_YEAR);
response.getHeaders().setExpires(new Date().getTime() + ONE_YEAR * 1000);
response.getHeaders().add(HttpHeaders.VARY, HttpHeaders.ORIGIN);
}
protected void addNoCacheHeaders(ServerHttpResponse response) {
@@ -536,15 +512,15 @@ public abstract class AbstractSockJsService implements SockJsService {
public void handle(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
if (HttpMethod.GET.equals(request.getMethod())) {
addNoCacheHeaders(response);
if (checkAndAddCorsHeaders(request, response)) {
if (checkOrigin(request, response)) {
response.getHeaders().setContentType(new MediaType("application", "json", UTF8_CHARSET));
String content = String.format(INFO_CONTENT, random.nextInt(), isSessionCookieNeeded(), isWebSocketEnabled());
response.getBody().write(content.getBytes());
}
}
else if (HttpMethod.OPTIONS.equals(request.getMethod())) {
if (checkAndAddCorsHeaders(request, response, HttpMethod.OPTIONS,
HttpMethod.GET)) {
if (checkOrigin(request, response)) {
addCacheHeaders(response);
response.setStatusCode(HttpStatus.NO_CONTENT);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2015 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.
@@ -27,6 +27,8 @@ import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.util.Assert;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.handler.ExceptionWebSocketHandlerDecorator;
@@ -39,9 +41,10 @@ import org.springframework.web.socket.sockjs.SockJsService;
* in a Servlet container.
*
* @author Rossen Stoyanchev
* @author Sebastien Deleuze
* @since 4.0
*/
public class SockJsHttpRequestHandler implements HttpRequestHandler {
public class SockJsHttpRequestHandler implements HttpRequestHandler, CorsConfigurationSource {
// No logging: HTTP transports too verbose and we don't know enough to log anything of value
@@ -100,4 +103,12 @@ public class SockJsHttpRequestHandler implements HttpRequestHandler {
return ((path.length() > 0) && (path.charAt(0) != '/')) ? "/" + path : path;
}
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
if (sockJsService instanceof CorsConfigurationSource) {
return ((CorsConfigurationSource)sockJsService).getCorsConfiguration(request);
}
return null;
}
}

View File

@@ -56,6 +56,7 @@ import org.springframework.web.socket.sockjs.support.AbstractSockJsService;
*
* @author Rossen Stoyanchev
* @author Juergen Hoeller
* @author Sebastien Deleuze
* @since 4.0
*/
public class TransportHandlingSockJsService extends AbstractSockJsService implements SockJsServiceConfig {
@@ -208,27 +209,27 @@ public class TransportHandlingSockJsService extends AbstractSockJsService implem
return;
}
HttpMethod supportedMethod = transportType.getHttpMethod();
if (!supportedMethod.equals(request.getMethod())) {
if (HttpMethod.OPTIONS.equals(request.getMethod()) && transportType.supportsCors()) {
if (checkAndAddCorsHeaders(request, response, HttpMethod.OPTIONS, supportedMethod)) {
response.setStatusCode(HttpStatus.NO_CONTENT);
addCacheHeaders(response);
}
}
else if (transportType.supportsCors()) {
sendMethodNotAllowed(response, supportedMethod, HttpMethod.OPTIONS);
}
else {
sendMethodNotAllowed(response, supportedMethod);
}
return;
}
HandshakeInterceptorChain chain = new HandshakeInterceptorChain(this.interceptors, handler);
SockJsException failure = null;
HandshakeInterceptorChain chain = new HandshakeInterceptorChain(this.interceptors, handler);
try {
HttpMethod supportedMethod = transportType.getHttpMethod();
if (!supportedMethod.equals(request.getMethod())) {
if (HttpMethod.OPTIONS.equals(request.getMethod()) && transportType.supportsCors()) {
if (checkOrigin(request, response, HttpMethod.OPTIONS, supportedMethod)) {
response.setStatusCode(HttpStatus.NO_CONTENT);
addCacheHeaders(response);
}
}
else if (transportType.supportsCors()) {
sendMethodNotAllowed(response, supportedMethod, HttpMethod.OPTIONS);
}
else {
sendMethodNotAllowed(response, supportedMethod);
}
return;
}
SockJsSession session = this.sessions.get(sessionId);
if (session == null) {
if (transportHandler instanceof SockJsSessionFactory) {
@@ -264,7 +265,7 @@ public class TransportHandlingSockJsService extends AbstractSockJsService implem
}
if (transportType.supportsCors()) {
if (!checkAndAddCorsHeaders(request, response)) {
if (!checkOrigin(request, response)) {
return;
}
}