Improve CORS handling

This commit improves CORS support by:
 - Using CORS processing only for CORS-enabled endpoints
 - Skipping CORS processing for same-origin requests
 - Adding Vary headers for non-CORS requests

It introduces an AbstractHandlerMapping#hasCorsConfigurationSource
method in order to be able to check CORS endpoints efficiently.

Closes gh-22273
Closes gh-22496
This commit is contained in:
Sebastien Deleuze
2019-04-01 14:36:38 +02:00
parent 8714710170
commit d27b5d0ab6
20 changed files with 278 additions and 123 deletions

View File

@@ -33,6 +33,7 @@ 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;
@@ -48,7 +49,6 @@ 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;
@@ -495,7 +495,7 @@ public abstract class AbstractSockJsService implements SockJsService, CorsConfig
@Override
@Nullable
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
if (!this.suppressCors && CorsUtils.isCorsRequest(request)) {
if (!this.suppressCors && (request.getHeader(HttpHeaders.ORIGIN) != null)) {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(new ArrayList<>(this.allowedOrigins));
config.addAllowedMethod("*");