Update CORS support

This commit updates CORS support in order to check Origin header
in CorsUtils#isPreFlightRequest which does not change how Spring
MVC or WebFlux process CORS request but is more correct in term
of behavior since it is a public API potentially used in another
contexts.

It also removes an unnecessary check in
AbstractHandlerMethodMapping#hasCorsConfigurationSource and processes
every preflight request with PreFlightHandler.

Closes gh-24327
This commit is contained in:
Sébastien Deleuze
2020-01-10 14:51:55 +01:00
parent 8396e6bdd1
commit bc7d010485
10 changed files with 74 additions and 26 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2020 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.
@@ -66,12 +66,12 @@ public abstract class CorsUtils {
}
/**
* Returns {@code true} if the request is a valid CORS pre-flight one.
* To be used in combination with {@link #isCorsRequest(HttpServletRequest)} since
* regular CORS checks are not invoked here for performance reasons.
* Returns {@code true} if the request is a valid CORS pre-flight one by checking {code OPTIONS} method with
* {@code Origin} and {@code Access-Control-Request-Method} headers presence.
*/
public static boolean isPreFlightRequest(HttpServletRequest request) {
return (HttpMethod.OPTIONS.matches(request.getMethod()) &&
request.getHeader(HttpHeaders.ORIGIN) != null &&
request.getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD) != null);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2020 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.
@@ -45,12 +45,14 @@ public abstract class CorsUtils {
}
/**
* Returns {@code true} if the request is a valid CORS pre-flight one.
* To be used in combination with {@link #isCorsRequest(ServerHttpRequest)} since
* regular CORS checks are not invoked here for performance reasons.
* Returns {@code true} if the request is a valid CORS pre-flight one by checking {code OPTIONS} method with
* {@code Origin} and {@code Access-Control-Request-Method} headers presence.
*/
public static boolean isPreFlightRequest(ServerHttpRequest request) {
return (request.getMethod() == HttpMethod.OPTIONS && request.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD));
HttpHeaders headers = request.getHeaders();
return (request.getMethod() == HttpMethod.OPTIONS
&& headers.containsKey(HttpHeaders.ORIGIN)
&& headers.containsKey(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD));
}
/**