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:
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* 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.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.web.bind.annotation;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Marks the annotated method as permitting cross origin requests.
|
||||
* By default, all origins and headers are permitted.
|
||||
*
|
||||
* @since 4.2
|
||||
* @author Russell Allen
|
||||
* @author Sebastien Deleuze
|
||||
*/
|
||||
@Target({ElementType.METHOD, ElementType.TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface CrossOrigin {
|
||||
|
||||
/**
|
||||
* List of allowed origins. {@code "*"} means that all origins are allowed. These values
|
||||
* are placed in the {@code Access-Control-Allow-Origin } header of both the pre-flight
|
||||
* and actual responses. Default value is <b>"*"</b>.
|
||||
*/
|
||||
String[] origin() default {"*"};
|
||||
|
||||
/**
|
||||
* Indicates which request headers can be used during the actual request. {@code "*"} means
|
||||
* that all headers asked by the client are allowed. This property controls the value of
|
||||
* pre-flight response's {@code Access-Control-Allow-Headers} header. Default value is
|
||||
* <b>"*"</b>.
|
||||
*/
|
||||
String[] allowedHeaders() default {"*"};
|
||||
|
||||
/**
|
||||
* List of response headers that the user-agent will allow the client to access. This property
|
||||
* controls the value of actual response's {@code Access-Control-Expose-Headers} header.
|
||||
*/
|
||||
String[] exposedHeaders() default {};
|
||||
|
||||
/**
|
||||
* The HTTP request methods to allow: GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE.
|
||||
* Methods specified here overrides {@code RequestMapping} ones.
|
||||
*/
|
||||
RequestMethod[] method() default {};
|
||||
|
||||
/**
|
||||
* Set to {@code "true"} if the the browser should include any cookies associated to the domain
|
||||
* of the request being annotated, or "false" if it should not. Empty string "" means undefined.
|
||||
* If true, the pre-flight response will include the header
|
||||
* {@code Access-Control-Allow-Credentials=true}. Default value is <b>"true"</b>.
|
||||
*/
|
||||
String allowCredentials() default "true";
|
||||
|
||||
/**
|
||||
* Controls the cache duration for pre-flight responses. Setting this to a reasonable
|
||||
* value can reduce the number of pre-flight request/response interaction required by
|
||||
* the browser. This property controls the value of the {@code Access-Control-Max-Age header}
|
||||
* in the pre-flight response. Value set to -1 means undefined. Default value is
|
||||
* <b>1800</b> seconds, or 30 minutes.
|
||||
*/
|
||||
long maxAge() default 1800;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
/*
|
||||
* 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.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.web.cors;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Represents the CORS configuration that stores various properties used to check if a
|
||||
* CORS request is allowed and to generate CORS response headers.
|
||||
*
|
||||
* @author Sebastien Deleuze
|
||||
* @author Rossen Stoyanchev
|
||||
* @since 4.2
|
||||
* @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommandation</a>
|
||||
*/
|
||||
public class CorsConfiguration {
|
||||
|
||||
private List<String> allowedOrigins;
|
||||
private List<String> allowedMethods;
|
||||
private List<String> allowedHeaders;
|
||||
private List<String> exposedHeaders;
|
||||
private Boolean allowCredentials;
|
||||
private Long maxAge;
|
||||
|
||||
public CorsConfiguration() {
|
||||
}
|
||||
|
||||
public CorsConfiguration(CorsConfiguration config) {
|
||||
if (config.allowedOrigins != null) {
|
||||
this.allowedOrigins = new ArrayList<String>(config.allowedOrigins);
|
||||
}
|
||||
if (config.allowCredentials != null) {
|
||||
this.allowCredentials = new Boolean(config.allowCredentials);
|
||||
}
|
||||
if (config.exposedHeaders != null) {
|
||||
this.exposedHeaders = new ArrayList<String>(config.exposedHeaders);
|
||||
}
|
||||
if (config.allowedMethods != null) {
|
||||
this.allowedMethods = new ArrayList<String>(config.allowedMethods);
|
||||
}
|
||||
if (config.allowedHeaders != null) {
|
||||
this.allowedHeaders = new ArrayList<String>(config.allowedHeaders);
|
||||
}
|
||||
if (config.maxAge != null) {
|
||||
this.maxAge = new Long(config.maxAge);
|
||||
}
|
||||
}
|
||||
|
||||
public CorsConfiguration combine(CorsConfiguration other) {
|
||||
CorsConfiguration config = new CorsConfiguration(this);
|
||||
|
||||
if (other.getAllowedOrigins() != null) {
|
||||
config.setAllowedOrigins(other.getAllowedOrigins());
|
||||
}
|
||||
if (other.getAllowedMethods() != null) {
|
||||
config.setAllowedMethods(other.getAllowedMethods());
|
||||
}
|
||||
if (other.getAllowedHeaders() != null) {
|
||||
config.setAllowedHeaders(other.getAllowedHeaders());
|
||||
}
|
||||
if (other.getExposedHeaders() != null) {
|
||||
config.setExposedHeaders(other.getExposedHeaders());
|
||||
}
|
||||
if (other.getMaxAge() != null) {
|
||||
config.setMaxAge(other.getMaxAge());
|
||||
}
|
||||
if (other.isAllowCredentials() != null) {
|
||||
config.setAllowCredentials(other.isAllowCredentials());
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #setAllowedOrigins(java.util.List)
|
||||
*/
|
||||
public List<String> getAllowedOrigins() {
|
||||
if (this.allowedOrigins != null) {
|
||||
return this.allowedOrigins.contains("*") ? Arrays.asList("*") : Collections.unmodifiableList(this.allowedOrigins);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set allowed origins that will define Access-Control-Allow-Origin response
|
||||
* header values (mandatory). For example "http://domain1.com", "http://domain2.com" ...
|
||||
* "*" means that all domains are allowed.
|
||||
*/
|
||||
public void setAllowedOrigins(List<String> allowedOrigins) {
|
||||
this.allowedOrigins = allowedOrigins;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #setAllowedOrigins(java.util.List)
|
||||
*/
|
||||
public void addAllowedOrigin(String allowedOrigin) {
|
||||
if (this.allowedOrigins == null) {
|
||||
this.allowedOrigins = new ArrayList<String>();
|
||||
}
|
||||
this.allowedOrigins.add(allowedOrigin);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #setAllowedMethods(java.util.List)
|
||||
*/
|
||||
public List<String> getAllowedMethods() {
|
||||
return this.allowedMethods == null ? null : Collections.unmodifiableList(this.allowedMethods);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set allow methods that will define Access-Control-Allow-Methods response header
|
||||
* values. For example "GET", "POST", "PUT" ... "*" means that all methods requested
|
||||
* by the client are allowed. If not set, allowed method is set to "GET".
|
||||
*
|
||||
*/
|
||||
public void setAllowedMethods(List<String> allowedMethods) {
|
||||
this.allowedMethods = allowedMethods;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #setAllowedMethods(java.util.List)
|
||||
*/
|
||||
public void addAllowedMethod(String allowedMethod) {
|
||||
if (this.allowedMethods == null) {
|
||||
this.allowedMethods = new ArrayList<String>();
|
||||
}
|
||||
this.allowedMethods.add(allowedMethod);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #setAllowedHeaders(java.util.List)
|
||||
*/
|
||||
public List<String> getAllowedHeaders() {
|
||||
return this.allowedHeaders == null ? null : Collections.unmodifiableList(this.allowedHeaders);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a list of request headers that will define Access-Control-Allow-Methods response
|
||||
* header values. If a header field name is one of the following, it is not required
|
||||
* to be listed: Cache-Control, Content-Language, Expires, Last-Modified, Pragma.
|
||||
* "*" means that all headers asked by the client will be allowed.
|
||||
*/
|
||||
public void setAllowedHeaders(List<String> allowedHeaders) {
|
||||
this.allowedHeaders = allowedHeaders;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #setAllowedHeaders(java.util.List)
|
||||
*/
|
||||
public void addAllowedHeader(String allowedHeader) {
|
||||
if (this.allowedHeaders == null) {
|
||||
this.allowedHeaders = new ArrayList<String>();
|
||||
}
|
||||
this.allowedHeaders.add(allowedHeader);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #setExposedHeaders(java.util.List)
|
||||
*/
|
||||
public List<String> getExposedHeaders() {
|
||||
return this.exposedHeaders == null ? null : Collections.unmodifiableList(this.exposedHeaders);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a list of response headers other than simple headers that the resource might use
|
||||
* and can be exposed. Simple response headers are: Cache-Control, Content-Language,
|
||||
* Content-Type, Expires, Last-Modified, Pragma.
|
||||
*/
|
||||
public void setExposedHeaders(List<String> exposedHeaders) {
|
||||
this.exposedHeaders = exposedHeaders;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #setExposedHeaders(java.util.List)
|
||||
*/
|
||||
public void addExposedHeader(String exposedHeader) {
|
||||
if (this.exposedHeaders == null) {
|
||||
this.exposedHeaders = new ArrayList<String>();
|
||||
}
|
||||
this.exposedHeaders.add(exposedHeader);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #setAllowCredentials(Boolean)
|
||||
*/
|
||||
public Boolean isAllowCredentials() {
|
||||
return this.allowCredentials;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates whether the resource supports user credentials.
|
||||
* Set the value of Access-Control-Allow-Credentials response header.
|
||||
*/
|
||||
public void setAllowCredentials(Boolean allowCredentials) {
|
||||
this.allowCredentials = allowCredentials;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #setMaxAge(Long)
|
||||
*/
|
||||
public Long getMaxAge() {
|
||||
return maxAge;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates how long (seconds) the results of a preflight request can be cached
|
||||
* in a preflight result cache.
|
||||
*/
|
||||
public void setMaxAge(Long maxAge) {
|
||||
this.maxAge = maxAge;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* 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.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.web.cors;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* Interface to be implemented by classes (usually HTTP request handlers) that provides
|
||||
* a {@link CorsConfiguration} instance based on the provided request.
|
||||
*
|
||||
* @author Sebastien Deleuze
|
||||
* @since 4.2
|
||||
*/
|
||||
public interface CorsConfigurationSource {
|
||||
|
||||
/**
|
||||
* Return a {@link CorsConfiguration} based on the incoming request.
|
||||
*/
|
||||
CorsConfiguration getCorsConfiguration(HttpServletRequest request);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* 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.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.web.cors;
|
||||
|
||||
import java.io.IOException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
/**
|
||||
* Interface to be implemented by classes that process CORS preflight and actual requests.
|
||||
*
|
||||
* @author Sebastien Deleuze
|
||||
* @since 4.2
|
||||
* @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommandation</a>
|
||||
*/
|
||||
public interface CorsProcessor {
|
||||
|
||||
/**
|
||||
* Process a pre-flight CORS request based on the provided {@link CorsConfiguration}.
|
||||
* If the request is not a valid CORS pre-flight request or if it does not comply with
|
||||
* the configuration, it should be rejected.
|
||||
* If the request is valid and comply with the configuration, this method adds the related
|
||||
* CORS headers to the response.
|
||||
*/
|
||||
boolean processPreFlightRequest(CorsConfiguration conf, HttpServletRequest request, HttpServletResponse response) throws IOException;
|
||||
|
||||
/**
|
||||
* Process a simple or actual CORS request based on the provided {@link CorsConfiguration}.
|
||||
* If the request is not a valid CORS simple or actual request or if it does not comply
|
||||
* with the configuration, it should be rejected.
|
||||
* If the request is valid and comply with the configuration, this method adds the related
|
||||
* CORS headers to the response.
|
||||
*/
|
||||
boolean processActualRequest(CorsConfiguration conf, HttpServletRequest request, HttpServletResponse response) throws IOException;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/*
|
||||
* 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.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.web.cors;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
/**
|
||||
* Utility class for CORS request handling based on the
|
||||
* <a href="http://www.w3.org/TR/cors/">CORS W3C recommandation</a>.
|
||||
*
|
||||
* @author Sebastien Deleuze
|
||||
* @since 4.2
|
||||
*/
|
||||
public class CorsUtils {
|
||||
|
||||
/**
|
||||
* The CORS {@code Access-Control-Request-Headers} request header field name.
|
||||
* @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommandation</a>
|
||||
*/
|
||||
public static final String ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers";
|
||||
/**
|
||||
* The CORS {@code Access-Control-Request-Method} request header field name.
|
||||
* @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommandation</a>
|
||||
*/
|
||||
public static final String ACCESS_CONTROL_REQUEST_METHOD = "Access-Control-Request-Method";
|
||||
/**
|
||||
* The CORS {@code Access-Control-Allow-Origin} response header field name.
|
||||
* @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommandation</a>
|
||||
*/
|
||||
public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
|
||||
/**
|
||||
* The CORS {@code Access-Control-Allow-Headers} response header field name.
|
||||
* @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommandation</a>
|
||||
*/
|
||||
public static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
|
||||
/**
|
||||
* The CORS {@code Access-Control-Allow-Methods} response header field name.
|
||||
* @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommandation</a>
|
||||
*/
|
||||
public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
|
||||
/**
|
||||
* The CORS {@code Access-Control-Max-Age} response header field name.
|
||||
* @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommandation</a>
|
||||
*/
|
||||
public static final String ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age";
|
||||
/**
|
||||
* The CORS {@code Access-Control-Allow-Credentials} response header field name.
|
||||
* @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommandation</a>
|
||||
*/
|
||||
public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
|
||||
/**
|
||||
* The CORS {@code Access-Control-Expose-Headers} response header field name.
|
||||
* @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommandation</a>
|
||||
*/
|
||||
public static final String ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers";
|
||||
|
||||
/**
|
||||
* Returns {@code true} if the request is a valid CORS one.
|
||||
*/
|
||||
public static boolean isCorsRequest(HttpServletRequest request) {
|
||||
return request.getHeader(HttpHeaders.ORIGIN) != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns {@code true} if the request is a valid CORS pre-flight one.
|
||||
*/
|
||||
public static boolean isPreFlightRequest(HttpServletRequest request) {
|
||||
if (!isCorsRequest(request)) {
|
||||
return false;
|
||||
}
|
||||
return request.getMethod().equals(HttpMethod.OPTIONS.name());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns {@code true} if the response already contains CORS headers.
|
||||
*/
|
||||
public static boolean isCorsResponse(HttpServletResponse response) {
|
||||
boolean hasCorsResponseHeaders = false;
|
||||
try {
|
||||
// Perhaps a CORS Filter has already added this?
|
||||
hasCorsResponseHeaders = !CollectionUtils.isEmpty(response.getHeaders(CorsUtils.ACCESS_CONTROL_ALLOW_ORIGIN));
|
||||
}
|
||||
catch (NullPointerException npe) {
|
||||
// See SPR-11919 and https://issues.jboss.org/browse/WFLY-3474
|
||||
}
|
||||
return hasCorsResponseHeaders;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
/*
|
||||
* 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.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.web.cors;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
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.util.StringUtils;
|
||||
|
||||
/**
|
||||
* Default implementation of {@link CorsProcessor}, as defined by the
|
||||
* <a href="http://www.w3.org/TR/cors/">CORS W3C recommandation</a>.
|
||||
*
|
||||
* @author Sebastien Deleuze
|
||||
* @since 4.2
|
||||
*/
|
||||
public class DefaultCorsProcessor implements CorsProcessor {
|
||||
|
||||
protected final Log logger = LogFactory.getLog(getClass());
|
||||
|
||||
@Override
|
||||
public boolean processPreFlightRequest(CorsConfiguration config, HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
if (!CorsUtils.isPreFlightRequest(request)) {
|
||||
rejectCorsRequest(response);
|
||||
return false;
|
||||
}
|
||||
if (check(request, response, config)) {
|
||||
setOriginHeader(request, response, config.getAllowedOrigins(), config.isAllowCredentials());
|
||||
setAllowCredentialsHeader(response, config.isAllowCredentials());
|
||||
setAllowMethodsHeader(request, response, config.getAllowedMethods());
|
||||
setAllowHeadersHeader(request, response, config.getAllowedHeaders());
|
||||
setMaxAgeHeader(response, config.getMaxAge());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean processActualRequest(CorsConfiguration config, HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
if (CorsUtils.isPreFlightRequest(request) || !CorsUtils.isCorsRequest(request)) {
|
||||
rejectCorsRequest(response);
|
||||
return false;
|
||||
}
|
||||
if (check(request, response, config)) {
|
||||
setOriginHeader(request, response, config.getAllowedOrigins(), config.isAllowCredentials());
|
||||
setAllowCredentialsHeader(response, config.isAllowCredentials());
|
||||
setExposeHeadersHeader(response, config.getExposedHeaders());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void rejectCorsRequest(HttpServletResponse response) throws IOException {
|
||||
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid CORS request");
|
||||
}
|
||||
|
||||
private boolean check(HttpServletRequest request, HttpServletResponse response, CorsConfiguration config) throws IOException {
|
||||
if (CorsUtils.isCorsResponse(response)) {
|
||||
logger.debug("Skip adding CORS headers, response already contains \"Access-Control-Allow-Origin\"");
|
||||
return false;
|
||||
}
|
||||
if (!(checkOrigin(request, config.getAllowedOrigins()) &&
|
||||
checkRequestMethod(request, config.getAllowedMethods()) &&
|
||||
checkRequestHeaders(request, config.getAllowedHeaders()))) {
|
||||
rejectCorsRequest(response);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean checkOrigin(HttpServletRequest request, List<String> allowedOrigins) {
|
||||
String origin = request.getHeader(HttpHeaders.ORIGIN);
|
||||
if ((origin == null) || (allowedOrigins == null)) {
|
||||
return false;
|
||||
}
|
||||
if (allowedOrigins.contains("*")) {
|
||||
return true;
|
||||
}
|
||||
for (String allowedOrigin : allowedOrigins) {
|
||||
if (origin.equalsIgnoreCase(allowedOrigin)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean checkRequestMethod(HttpServletRequest request, List<String> allowedMethods) {
|
||||
String requestMethod = CorsUtils.isPreFlightRequest(request) ?
|
||||
request.getHeader(CorsUtils.ACCESS_CONTROL_REQUEST_METHOD) : request.getMethod();
|
||||
if (requestMethod == null) {
|
||||
return false;
|
||||
}
|
||||
if (allowedMethods == null) {
|
||||
allowedMethods = Arrays.asList(HttpMethod.GET.name());
|
||||
}
|
||||
if (allowedMethods.contains("*")) {
|
||||
return true;
|
||||
}
|
||||
for (String allowedMethod : allowedMethods) {
|
||||
if (requestMethod.equalsIgnoreCase(allowedMethod)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean checkRequestHeaders(HttpServletRequest request, List<String> allowedHeaders) {
|
||||
String[] requestHeaders = CorsUtils.isPreFlightRequest(request) ?
|
||||
StringUtils.commaDelimitedListToStringArray(request.getHeader(CorsUtils.ACCESS_CONTROL_REQUEST_HEADERS)) :
|
||||
Collections.list(request.getHeaderNames()).toArray(new String [0]);
|
||||
|
||||
if ((allowedHeaders != null) && allowedHeaders.contains("*")) {
|
||||
return true;
|
||||
}
|
||||
for (String requestHeader : requestHeaders) {
|
||||
if (!HttpHeaders.ORIGIN.equals(requestHeader)) {
|
||||
requestHeader = requestHeader.trim();
|
||||
boolean found = false;
|
||||
if (allowedHeaders != null) {
|
||||
for (String header : allowedHeaders) {
|
||||
if (requestHeader.equalsIgnoreCase(header)) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void setOriginHeader(HttpServletRequest request, HttpServletResponse response, List<String> allowedOrigins, Boolean allowCredentials) {
|
||||
String origin = request.getHeader(HttpHeaders.ORIGIN);
|
||||
if (allowedOrigins.contains("*") && (allowCredentials == null || !allowCredentials)) {
|
||||
response.addHeader(CorsUtils.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
|
||||
return;
|
||||
}
|
||||
response.addHeader(CorsUtils.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
|
||||
response.addHeader(HttpHeaders.VARY, HttpHeaders.ORIGIN);
|
||||
}
|
||||
|
||||
private void setAllowCredentialsHeader(HttpServletResponse response, Boolean allowCredentials) {
|
||||
if ((allowCredentials != null) && allowCredentials) {
|
||||
response.addHeader(CorsUtils.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
|
||||
}
|
||||
}
|
||||
|
||||
private void setAllowMethodsHeader(HttpServletRequest request, HttpServletResponse response, List<String> allowedMethods) {
|
||||
if (allowedMethods == null) {
|
||||
allowedMethods = Arrays.asList(HttpMethod.GET.name());
|
||||
}
|
||||
if (allowedMethods.contains("*")) {
|
||||
response.addHeader(CorsUtils.ACCESS_CONTROL_ALLOW_METHODS, request.getHeader(CorsUtils.ACCESS_CONTROL_REQUEST_METHOD));
|
||||
}
|
||||
else {
|
||||
response.addHeader(CorsUtils.ACCESS_CONTROL_ALLOW_METHODS, StringUtils.collectionToCommaDelimitedString(allowedMethods));
|
||||
}
|
||||
}
|
||||
|
||||
private void setAllowHeadersHeader(HttpServletRequest request, HttpServletResponse response, List<String> allowedHeaders) {
|
||||
if ((allowedHeaders != null) && !allowedHeaders.isEmpty()) {
|
||||
String[] requestHeaders = StringUtils.commaDelimitedListToStringArray(request.getHeader(CorsUtils.ACCESS_CONTROL_REQUEST_HEADERS));
|
||||
boolean matchAll = allowedHeaders.contains("*");
|
||||
List<String> matchingHeaders = new ArrayList<String>();
|
||||
for (String requestHeader : requestHeaders) {
|
||||
for (String header : allowedHeaders) {
|
||||
requestHeader = requestHeader.trim();
|
||||
if (matchAll || requestHeader.equalsIgnoreCase(header)) {
|
||||
matchingHeaders.add(requestHeader);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!matchingHeaders.isEmpty()) {
|
||||
response.addHeader(CorsUtils.ACCESS_CONTROL_ALLOW_HEADERS, StringUtils.collectionToCommaDelimitedString(matchingHeaders));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void setExposeHeadersHeader(HttpServletResponse response, List<String> exposedHeaders) {
|
||||
if ((exposedHeaders != null) && !exposedHeaders.isEmpty()) {
|
||||
response.addHeader(CorsUtils.ACCESS_CONTROL_EXPOSE_HEADERS, StringUtils.collectionToCommaDelimitedString(exposedHeaders));
|
||||
}
|
||||
}
|
||||
|
||||
private void setMaxAgeHeader(HttpServletResponse response, Long maxAge) {
|
||||
if (maxAge != null) {
|
||||
response.addHeader(CorsUtils.ACCESS_CONTROL_MAX_AGE, maxAge.toString());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user