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:
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,6 @@ package org.springframework.web.socket;
|
||||
|
||||
import org.junit.Before;
|
||||
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.server.ServerHttpAsyncRequestControl;
|
||||
import org.springframework.http.server.ServerHttpRequest;
|
||||
import org.springframework.http.server.ServerHttpResponse;
|
||||
@@ -55,10 +54,6 @@ public abstract class AbstractHttpRequestTests {
|
||||
this.servletRequest.setRequestURI(requestUri);
|
||||
}
|
||||
|
||||
protected void setOrigin(String origin) {
|
||||
this.request.getHeaders().add(HttpHeaders.ORIGIN, origin);
|
||||
}
|
||||
|
||||
protected void resetRequestAndResponse() {
|
||||
resetRequest();
|
||||
resetResponse();
|
||||
|
||||
@@ -26,6 +26,7 @@ import static org.junit.Assert.*;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.socket.AbstractHttpRequestTests;
|
||||
import org.springframework.web.socket.WebSocketHandler;
|
||||
@@ -61,7 +62,7 @@ public class OriginHandshakeInterceptorTests extends AbstractHttpRequestTests {
|
||||
public void originValueMatch() throws Exception {
|
||||
Map<String, Object> attributes = new HashMap<String, Object>();
|
||||
WebSocketHandler wsHandler = Mockito.mock(WebSocketHandler.class);
|
||||
setOrigin("http://mydomain1.com");
|
||||
this.servletRequest.addHeader(HttpHeaders.ORIGIN, "http://mydomain1.com");
|
||||
OriginHandshakeInterceptor interceptor = new OriginHandshakeInterceptor(Arrays.asList("http://mydomain1.com"));
|
||||
assertTrue(interceptor.beforeHandshake(request, response, wsHandler, attributes));
|
||||
assertNotEquals(servletResponse.getStatus(), HttpStatus.FORBIDDEN.value());
|
||||
@@ -71,7 +72,7 @@ public class OriginHandshakeInterceptorTests extends AbstractHttpRequestTests {
|
||||
public void originValueNoMatch() throws Exception {
|
||||
Map<String, Object> attributes = new HashMap<String, Object>();
|
||||
WebSocketHandler wsHandler = Mockito.mock(WebSocketHandler.class);
|
||||
setOrigin("http://mydomain1.com");
|
||||
this.servletRequest.addHeader(HttpHeaders.ORIGIN, "http://mydomain1.com");
|
||||
OriginHandshakeInterceptor interceptor = new OriginHandshakeInterceptor(Arrays.asList("http://mydomain2.com"));
|
||||
assertFalse(interceptor.beforeHandshake(request, response, wsHandler, attributes));
|
||||
assertEquals(servletResponse.getStatus(), HttpStatus.FORBIDDEN.value());
|
||||
@@ -81,7 +82,7 @@ public class OriginHandshakeInterceptorTests extends AbstractHttpRequestTests {
|
||||
public void originListMatch() throws Exception {
|
||||
Map<String, Object> attributes = new HashMap<String, Object>();
|
||||
WebSocketHandler wsHandler = Mockito.mock(WebSocketHandler.class);
|
||||
setOrigin("http://mydomain2.com");
|
||||
this.servletRequest.addHeader(HttpHeaders.ORIGIN, "http://mydomain2.com");
|
||||
OriginHandshakeInterceptor interceptor = new OriginHandshakeInterceptor(Arrays.asList("http://mydomain1.com", "http://mydomain2.com", "http://mydomain3.com"));
|
||||
assertTrue(interceptor.beforeHandshake(request, response, wsHandler, attributes));
|
||||
assertNotEquals(servletResponse.getStatus(), HttpStatus.FORBIDDEN.value());
|
||||
@@ -91,7 +92,7 @@ public class OriginHandshakeInterceptorTests extends AbstractHttpRequestTests {
|
||||
public void originListNoMatch() throws Exception {
|
||||
Map<String, Object> attributes = new HashMap<String, Object>();
|
||||
WebSocketHandler wsHandler = Mockito.mock(WebSocketHandler.class);
|
||||
setOrigin("http://mydomain4.com");
|
||||
this.servletRequest.addHeader(HttpHeaders.ORIGIN, "http://mydomain4.com");
|
||||
OriginHandshakeInterceptor interceptor = new OriginHandshakeInterceptor(Arrays.asList("http://mydomain1.com", "http://mydomain2.com", "http://mydomain3.com"));
|
||||
assertFalse(interceptor.beforeHandshake(request, response, wsHandler, attributes));
|
||||
assertEquals(servletResponse.getStatus(), HttpStatus.FORBIDDEN.value());
|
||||
@@ -101,7 +102,7 @@ public class OriginHandshakeInterceptorTests extends AbstractHttpRequestTests {
|
||||
public void originNoMatchWithNullHostileCollection() throws Exception {
|
||||
Map<String, Object> attributes = new HashMap<String, Object>();
|
||||
WebSocketHandler wsHandler = Mockito.mock(WebSocketHandler.class);
|
||||
setOrigin("http://mydomain4.com");
|
||||
this.servletRequest.addHeader(HttpHeaders.ORIGIN, "http://mydomain4.com");
|
||||
OriginHandshakeInterceptor interceptor = new OriginHandshakeInterceptor();
|
||||
Set<String> allowedOrigins = new ConcurrentSkipListSet<String>();
|
||||
allowedOrigins.add("http://mydomain1.com");
|
||||
@@ -114,7 +115,7 @@ public class OriginHandshakeInterceptorTests extends AbstractHttpRequestTests {
|
||||
public void originMatchAll() throws Exception {
|
||||
Map<String, Object> attributes = new HashMap<String, Object>();
|
||||
WebSocketHandler wsHandler = Mockito.mock(WebSocketHandler.class);
|
||||
setOrigin("http://mydomain1.com");
|
||||
this.servletRequest.addHeader(HttpHeaders.ORIGIN, "http://mydomain1.com");
|
||||
OriginHandshakeInterceptor interceptor = new OriginHandshakeInterceptor();
|
||||
interceptor.setAllowedOrigins(Arrays.asList("*"));
|
||||
assertTrue(interceptor.beforeHandshake(request, response, wsHandler, attributes));
|
||||
@@ -125,7 +126,7 @@ public class OriginHandshakeInterceptorTests extends AbstractHttpRequestTests {
|
||||
public void sameOriginMatch() throws Exception {
|
||||
Map<String, Object> attributes = new HashMap<String, Object>();
|
||||
WebSocketHandler wsHandler = Mockito.mock(WebSocketHandler.class);
|
||||
setOrigin("http://mydomain2.com");
|
||||
this.servletRequest.addHeader(HttpHeaders.ORIGIN, "http://mydomain2.com");
|
||||
this.servletRequest.setServerName("mydomain2.com");
|
||||
OriginHandshakeInterceptor interceptor = new OriginHandshakeInterceptor(Arrays.asList());
|
||||
assertTrue(interceptor.beforeHandshake(request, response, wsHandler, attributes));
|
||||
@@ -136,7 +137,7 @@ public class OriginHandshakeInterceptorTests extends AbstractHttpRequestTests {
|
||||
public void sameOriginNoMatch() throws Exception {
|
||||
Map<String, Object> attributes = new HashMap<String, Object>();
|
||||
WebSocketHandler wsHandler = Mockito.mock(WebSocketHandler.class);
|
||||
setOrigin("http://mydomain3.com");
|
||||
this.servletRequest.addHeader(HttpHeaders.ORIGIN, "http://mydomain3.com");
|
||||
this.servletRequest.setServerName("mydomain2.com");
|
||||
OriginHandshakeInterceptor interceptor = new OriginHandshakeInterceptor(Arrays.asList());
|
||||
assertFalse(interceptor.beforeHandshake(request, response, wsHandler, attributes));
|
||||
|
||||
@@ -26,12 +26,14 @@ import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.server.ServerHttpRequest;
|
||||
import org.springframework.http.server.ServerHttpResponse;
|
||||
import org.springframework.http.server.ServletServerHttpResponse;
|
||||
import org.springframework.scheduling.TaskScheduler;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
|
||||
import org.springframework.web.cors.CorsUtils;
|
||||
import org.springframework.web.socket.AbstractHttpRequestTests;
|
||||
import org.springframework.web.socket.WebSocketHandler;
|
||||
import org.springframework.web.socket.sockjs.SockJsException;
|
||||
@@ -84,10 +86,10 @@ public class SockJsServiceTests extends AbstractHttpRequestTests {
|
||||
resetResponseAndHandleRequest("GET", "/echo/info", HttpStatus.OK);
|
||||
|
||||
assertEquals("application/json;charset=UTF-8", this.servletResponse.getContentType());
|
||||
assertEquals("no-store, no-cache, must-revalidate, max-age=0", this.servletResponse.getHeader("Cache-Control"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Origin"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Credentials"));
|
||||
assertNull(this.servletResponse.getHeader("Vary"));
|
||||
assertEquals("no-store, no-cache, must-revalidate, max-age=0", this.servletResponse.getHeader(HttpHeaders.CACHE_CONTROL));
|
||||
assertNull(this.servletResponse.getHeader(CorsUtils.ACCESS_CONTROL_ALLOW_ORIGIN));
|
||||
assertNull(this.servletResponse.getHeader(CorsUtils.ACCESS_CONTROL_ALLOW_CREDENTIALS));
|
||||
assertNull(this.servletResponse.getHeader(HttpHeaders.VARY));
|
||||
|
||||
String body = this.servletResponse.getContentAsString();
|
||||
assertEquals("{\"entropy\"", body.substring(0, body.indexOf(':')));
|
||||
@@ -104,56 +106,42 @@ public class SockJsServiceTests extends AbstractHttpRequestTests {
|
||||
|
||||
this.service.setAllowedOrigins(Arrays.asList("http://mydomain1.com"));
|
||||
resetResponseAndHandleRequest("GET", "/echo/info", HttpStatus.OK);
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Origin"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Credentials"));
|
||||
assertNull(this.servletResponse.getHeader("Vary"));
|
||||
assertNull(this.servletResponse.getHeader(CorsUtils.ACCESS_CONTROL_ALLOW_ORIGIN));
|
||||
assertNull(this.servletResponse.getHeader(CorsUtils.ACCESS_CONTROL_ALLOW_CREDENTIALS));
|
||||
assertNull(this.servletResponse.getHeader(HttpHeaders.VARY));
|
||||
}
|
||||
|
||||
@Test // SPR-12226 and SPR-12660
|
||||
public void handleInfoGetWithOrigin() throws Exception {
|
||||
this.servletRequest.setServerName("mydomain2.com");
|
||||
setOrigin("http://mydomain2.com");
|
||||
this.servletRequest.addHeader(HttpHeaders.ORIGIN, "http://mydomain2.com");
|
||||
resetResponseAndHandleRequest("GET", "/echo/info", HttpStatus.OK);
|
||||
|
||||
assertEquals("application/json;charset=UTF-8", this.servletResponse.getContentType());
|
||||
assertEquals("no-store, no-cache, must-revalidate, max-age=0", this.servletResponse.getHeader("Cache-Control"));
|
||||
assertEquals("http://mydomain2.com", this.servletResponse.getHeader("Access-Control-Allow-Origin"));
|
||||
assertEquals("true", this.servletResponse.getHeader("Access-Control-Allow-Credentials"));
|
||||
assertEquals("Origin", this.servletResponse.getHeader("Vary"));
|
||||
|
||||
assertEquals("no-store, no-cache, must-revalidate, max-age=0", this.servletResponse.getHeader(HttpHeaders.CACHE_CONTROL));
|
||||
String body = this.servletResponse.getContentAsString();
|
||||
assertEquals("{\"entropy\"", body.substring(0, body.indexOf(':')));
|
||||
assertEquals(",\"origins\":[\"*:*\"],\"cookie_needed\":true,\"websocket\":true}",
|
||||
body.substring(body.indexOf(',')));
|
||||
assertEquals(",\"origins\":[\"*:*\"],\"cookie_needed\":true,\"websocket\":true}", body.substring(body.indexOf(',')));
|
||||
|
||||
this.service.setAllowedOrigins(Arrays.asList("http://mydomain1.com"));
|
||||
resetResponseAndHandleRequest("GET", "/echo/info", HttpStatus.FORBIDDEN);
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Origin"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Credentials"));
|
||||
assertNull(this.servletResponse.getHeader("Vary"));
|
||||
|
||||
this.service.setAllowedOrigins(Arrays.asList("http://mydomain1.com", "http://mydomain2.com", "http://mydomain3.com"));
|
||||
resetResponseAndHandleRequest("GET", "/echo/info", HttpStatus.OK);
|
||||
assertEquals("http://mydomain2.com", this.servletResponse.getHeader("Access-Control-Allow-Origin"));
|
||||
assertEquals("true", this.servletResponse.getHeader("Access-Control-Allow-Credentials"));
|
||||
assertEquals("Origin", this.servletResponse.getHeader("Vary"));
|
||||
|
||||
this.service.setAllowedOrigins(Arrays.asList("*"));
|
||||
resetResponseAndHandleRequest("GET", "/echo/info", HttpStatus.OK);
|
||||
assertEquals("http://mydomain2.com", this.servletResponse.getHeader("Access-Control-Allow-Origin"));
|
||||
assertEquals("true", this.servletResponse.getHeader("Access-Control-Allow-Credentials"));
|
||||
assertEquals("Origin", this.servletResponse.getHeader("Vary"));
|
||||
}
|
||||
|
||||
@Test // SPR-11443
|
||||
public void handleInfoGetCorsFilter() throws Exception {
|
||||
|
||||
// Simulate scenario where Filter would have already set CORS headers
|
||||
this.servletResponse.setHeader("Access-Control-Allow-Origin", "foobar:123");
|
||||
this.servletResponse.setHeader(CorsUtils.ACCESS_CONTROL_ALLOW_ORIGIN, "foobar:123");
|
||||
|
||||
handleRequest("GET", "/echo/info", HttpStatus.OK);
|
||||
|
||||
assertEquals("foobar:123", this.servletResponse.getHeader("Access-Control-Allow-Origin"));
|
||||
assertEquals("foobar:123", this.servletResponse.getHeader(CorsUtils.ACCESS_CONTROL_ALLOW_ORIGIN));
|
||||
}
|
||||
|
||||
@Test // SPR-11919
|
||||
@@ -161,7 +149,7 @@ public class SockJsServiceTests extends AbstractHttpRequestTests {
|
||||
public void handleInfoGetWildflyNPE() throws Exception {
|
||||
HttpServletResponse mockResponse = mock(HttpServletResponse.class);
|
||||
ServletOutputStream ous = mock(ServletOutputStream.class);
|
||||
given(mockResponse.getHeaders("Access-Control-Allow-Origin")).willThrow(NullPointerException.class);
|
||||
given(mockResponse.getHeaders(CorsUtils.ACCESS_CONTROL_ALLOW_ORIGIN)).willThrow(NullPointerException.class);
|
||||
given(mockResponse.getOutputStream()).willReturn(ous);
|
||||
this.response = new ServletServerHttpResponse(mockResponse);
|
||||
|
||||
@@ -172,107 +160,53 @@ public class SockJsServiceTests extends AbstractHttpRequestTests {
|
||||
|
||||
@Test // SPR-12660
|
||||
public void handleInfoOptions() throws Exception {
|
||||
this.servletRequest.addHeader("Access-Control-Request-Headers", "Last-Modified");
|
||||
this.servletRequest.addHeader(CorsUtils.ACCESS_CONTROL_REQUEST_HEADERS, "Last-Modified");
|
||||
resetResponseAndHandleRequest("OPTIONS", "/echo/info", HttpStatus.NO_CONTENT);
|
||||
this.response.flush();
|
||||
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Origin"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Credentials"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Headers"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Methods"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Max-Age"));
|
||||
assertEquals("Origin", this.servletResponse.getHeader("Vary"));
|
||||
assertNull(this.service.getCorsConfiguration(this.servletRequest));
|
||||
|
||||
this.service.setAllowedOrigins(Arrays.asList("http://mydomain1.com"));
|
||||
resetResponseAndHandleRequest("OPTIONS", "/echo/info", HttpStatus.NO_CONTENT);
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Origin"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Credentials"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Headers"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Methods"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Max-Age"));
|
||||
assertEquals("Origin", this.servletResponse.getHeader("Vary"));
|
||||
assertNull(this.service.getCorsConfiguration(this.servletRequest));
|
||||
}
|
||||
|
||||
@Test // SPR-12226 and SPR-12660
|
||||
public void handleInfoOptionsWithOrigin() throws Exception {
|
||||
this.servletRequest.setServerName("mydomain2.com");
|
||||
setOrigin("http://mydomain2.com");
|
||||
this.request.getHeaders().add("Access-Control-Request-Headers", "Last-Modified");
|
||||
this.servletRequest.addHeader(HttpHeaders.ORIGIN, "http://mydomain2.com");
|
||||
this.servletRequest.addHeader(CorsUtils.ACCESS_CONTROL_REQUEST_METHOD, "GET");
|
||||
this.servletRequest.addHeader(CorsUtils.ACCESS_CONTROL_REQUEST_HEADERS, "Last-Modified");
|
||||
resetResponseAndHandleRequest("OPTIONS", "/echo/info", HttpStatus.NO_CONTENT);
|
||||
this.response.flush();
|
||||
assertEquals("http://mydomain2.com", this.servletResponse.getHeader("Access-Control-Allow-Origin"));
|
||||
assertEquals("true", this.servletResponse.getHeader("Access-Control-Allow-Credentials"));
|
||||
assertEquals("Last-Modified", this.servletResponse.getHeader("Access-Control-Allow-Headers"));
|
||||
assertEquals("OPTIONS, GET", this.servletResponse.getHeader("Access-Control-Allow-Methods"));
|
||||
assertEquals("31536000", this.servletResponse.getHeader("Access-Control-Max-Age"));
|
||||
assertEquals("Origin", this.servletResponse.getHeader("Vary"));
|
||||
assertNotNull(this.service.getCorsConfiguration(this.servletRequest));
|
||||
|
||||
this.service.setAllowedOrigins(Arrays.asList("http://mydomain1.com"));
|
||||
resetResponseAndHandleRequest("OPTIONS", "/echo/info", HttpStatus.FORBIDDEN);
|
||||
this.response.flush();
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Origin"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Credentials"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Headers"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Methods"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Max-Age"));
|
||||
assertNull(this.servletResponse.getHeader("Vary"));
|
||||
|
||||
this.service.setAllowedOrigins(Arrays.asList("http://mydomain1.com", "http://mydomain2.com", "http://mydomain3.com"));
|
||||
resetResponseAndHandleRequest("OPTIONS", "/echo/info", HttpStatus.NO_CONTENT);
|
||||
this.response.flush();
|
||||
assertEquals("http://mydomain2.com", this.servletResponse.getHeader("Access-Control-Allow-Origin"));
|
||||
assertEquals("true", this.servletResponse.getHeader("Access-Control-Allow-Credentials"));
|
||||
assertEquals("Last-Modified", this.servletResponse.getHeader("Access-Control-Allow-Headers"));
|
||||
assertEquals("OPTIONS, GET", this.servletResponse.getHeader("Access-Control-Allow-Methods"));
|
||||
assertEquals("31536000", this.servletResponse.getHeader("Access-Control-Max-Age"));
|
||||
assertEquals("Origin", this.servletResponse.getHeader("Vary"));
|
||||
assertNotNull(this.service.getCorsConfiguration(this.servletRequest));
|
||||
|
||||
this.service.setAllowedOrigins(Arrays.asList("*"));
|
||||
resetResponseAndHandleRequest("OPTIONS", "/echo/info", HttpStatus.NO_CONTENT);
|
||||
this.response.flush();
|
||||
assertEquals("http://mydomain2.com", this.servletResponse.getHeader("Access-Control-Allow-Origin"));
|
||||
assertEquals("true", this.servletResponse.getHeader("Access-Control-Allow-Credentials"));
|
||||
assertEquals("Last-Modified", this.servletResponse.getHeader("Access-Control-Allow-Headers"));
|
||||
assertEquals("OPTIONS, GET", this.servletResponse.getHeader("Access-Control-Allow-Methods"));
|
||||
assertEquals("31536000", this.servletResponse.getHeader("Access-Control-Max-Age"));
|
||||
assertEquals("Origin", this.servletResponse.getHeader("Vary"));
|
||||
assertNotNull(this.service.getCorsConfiguration(this.servletRequest));
|
||||
}
|
||||
|
||||
@Test // SPR-12283
|
||||
public void handleInfoOptionsWithOriginAndCorsHeadersDisabled() throws Exception {
|
||||
setOrigin("http://mydomain2.com");
|
||||
this.servletRequest.addHeader(HttpHeaders.ORIGIN, "http://mydomain2.com");
|
||||
this.service.setAllowedOrigins(Arrays.asList("*"));
|
||||
this.service.setSuppressCors(true);
|
||||
|
||||
this.servletRequest.addHeader("Access-Control-Request-Headers", "Last-Modified");
|
||||
this.servletRequest.addHeader(CorsUtils.ACCESS_CONTROL_REQUEST_HEADERS, "Last-Modified");
|
||||
resetResponseAndHandleRequest("OPTIONS", "/echo/info", HttpStatus.NO_CONTENT);
|
||||
this.response.flush();
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Origin"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Credentials"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Headers"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Methods"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Max-Age"));
|
||||
assertEquals("Origin", this.servletResponse.getHeader("Vary"));
|
||||
assertNull(this.service.getCorsConfiguration(this.servletRequest));
|
||||
|
||||
this.service.setAllowedOrigins(Arrays.asList("http://mydomain1.com"));
|
||||
resetResponseAndHandleRequest("OPTIONS", "/echo/info", HttpStatus.FORBIDDEN);
|
||||
this.response.flush();
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Origin"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Credentials"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Headers"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Methods"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Max-Age"));
|
||||
assertNull(this.servletResponse.getHeader("Vary"));
|
||||
assertNull(this.service.getCorsConfiguration(this.servletRequest));
|
||||
|
||||
this.service.setAllowedOrigins(Arrays.asList("http://mydomain1.com", "http://mydomain2.com", "http://mydomain3.com"));
|
||||
resetResponseAndHandleRequest("OPTIONS", "/echo/info", HttpStatus.NO_CONTENT);
|
||||
this.response.flush();
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Origin"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Credentials"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Headers"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Methods"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Max-Age"));
|
||||
assertEquals("Origin", this.servletResponse.getHeader("Vary"));
|
||||
assertNull(this.service.getCorsConfiguration(this.servletRequest));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -26,7 +26,9 @@ import org.junit.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.scheduling.TaskScheduler;
|
||||
import org.springframework.web.cors.CorsUtils;
|
||||
import org.springframework.web.socket.AbstractHttpRequestTests;
|
||||
import org.springframework.web.socket.WebSocketHandler;
|
||||
import org.springframework.web.socket.handler.TestPrincipal;
|
||||
@@ -163,8 +165,8 @@ public class DefaultSockJsServiceTests extends AbstractHttpRequestTests {
|
||||
verify(taskScheduler).scheduleAtFixedRate(any(Runnable.class), eq(service.getDisconnectDelay()));
|
||||
|
||||
assertEquals("no-store, no-cache, must-revalidate, max-age=0", this.response.getHeaders().getCacheControl());
|
||||
assertNull(this.response.getHeaders().getFirst("Access-Control-Allow-Origin"));
|
||||
assertNull(this.response.getHeaders().getFirst("Access-Control-Allow-Credentials"));
|
||||
assertNull(this.servletResponse.getHeader(CorsUtils.ACCESS_CONTROL_ALLOW_ORIGIN));
|
||||
assertNull(this.servletResponse.getHeader(CorsUtils.ACCESS_CONTROL_ALLOW_CREDENTIALS));
|
||||
}
|
||||
|
||||
@Test // SPR-12226
|
||||
@@ -172,12 +174,10 @@ public class DefaultSockJsServiceTests extends AbstractHttpRequestTests {
|
||||
String sockJsPath = sessionUrlPrefix + "xhr";
|
||||
setRequest("POST", sockJsPrefix + sockJsPath);
|
||||
this.service.setAllowedOrigins(Arrays.asList("http://mydomain1.com", "http://mydomain2.com"));
|
||||
setOrigin("http://mydomain1.com");
|
||||
this.servletRequest.addHeader(HttpHeaders.ORIGIN, "http://mydomain1.com");
|
||||
this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler);
|
||||
|
||||
assertEquals(200, this.servletResponse.getStatus());
|
||||
assertEquals("http://mydomain1.com", this.response.getHeaders().getFirst("Access-Control-Allow-Origin"));
|
||||
assertEquals("true", this.response.getHeaders().getFirst("Access-Control-Allow-Credentials"));
|
||||
}
|
||||
|
||||
@Test // SPR-12226
|
||||
@@ -185,12 +185,10 @@ public class DefaultSockJsServiceTests extends AbstractHttpRequestTests {
|
||||
String sockJsPath = sessionUrlPrefix + "xhr";
|
||||
setRequest("POST", sockJsPrefix + sockJsPath);
|
||||
this.service.setAllowedOrigins(Arrays.asList("http://mydomain1.com", "http://mydomain2.com"));
|
||||
setOrigin("http://mydomain3.com");
|
||||
this.servletRequest.addHeader(HttpHeaders.ORIGIN, "http://mydomain3.com");
|
||||
this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler);
|
||||
|
||||
assertEquals(403, this.servletResponse.getStatus());
|
||||
assertNull(this.response.getHeaders().getFirst("Access-Control-Allow-Origin"));
|
||||
assertNull(this.response.getHeaders().getFirst("Access-Control-Allow-Credentials"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -200,9 +198,9 @@ public class DefaultSockJsServiceTests extends AbstractHttpRequestTests {
|
||||
this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler);
|
||||
|
||||
assertEquals(204, this.servletResponse.getStatus());
|
||||
assertNull(this.response.getHeaders().getFirst("Access-Control-Allow-Origin"));
|
||||
assertNull(this.response.getHeaders().getFirst("Access-Control-Allow-Credentials"));
|
||||
assertNull(this.response.getHeaders().getFirst("Access-Control-Allow-Methods"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Origin"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Credentials"));
|
||||
assertNull(this.servletResponse.getHeader("Access-Control-Allow-Methods"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -294,13 +292,13 @@ public class DefaultSockJsServiceTests extends AbstractHttpRequestTests {
|
||||
OriginHandshakeInterceptor interceptor = new OriginHandshakeInterceptor(Arrays.asList("http://mydomain1.com"));
|
||||
wsService.setHandshakeInterceptors(Arrays.asList(interceptor));
|
||||
setRequest("GET", sockJsPrefix + sockJsPath);
|
||||
setOrigin("http://mydomain1.com");
|
||||
this.servletRequest.addHeader(HttpHeaders.ORIGIN, "http://mydomain1.com");
|
||||
wsService.handleRequest(this.request, this.response, sockJsPath, this.wsHandler);
|
||||
assertNotEquals(403, this.servletResponse.getStatus());
|
||||
|
||||
resetRequestAndResponse();
|
||||
setRequest("GET", sockJsPrefix + sockJsPath);
|
||||
setOrigin("http://mydomain2.com");
|
||||
this.servletRequest.addHeader(HttpHeaders.ORIGIN, "http://mydomain2.com");
|
||||
wsService.handleRequest(this.request, this.response, sockJsPath, this.wsHandler);
|
||||
assertEquals(403, this.servletResponse.getStatus());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user