Class CorsConfiguration
By default a newly created CorsConfiguration does not permit any
cross-origin requests and must be configured explicitly to indicate what
should be allowed. Use applyPermitDefaultValues() to flip the
initialization model to start with open defaults that permit all cross-origin
requests for GET, HEAD, and POST requests.
- Since:
- 4.2
- Author:
- Sebastien Deleuze, Rossen Stoyanchev, Juergen Hoeller, Sam Brannen, Ruslan Akhundov
- See Also:
-
Field Summary
Fields -
Constructor Summary
ConstructorsConstructorDescriptionConstruct a newCorsConfigurationinstance with no cross-origin requests allowed for any origin by default.Construct a newCorsConfigurationinstance by copying all values from the suppliedCorsConfiguration. -
Method Summary
Modifier and TypeMethodDescriptionvoidaddAllowedHeader(String allowedHeader) Variant ofsetAllowedHeaders(List)for adding one allowed header at a time.voidaddAllowedMethod(String method) Variant ofsetAllowedMethods(java.util.List<java.lang.String>)for adding one allowed method at a time.voidaddAllowedMethod(HttpMethod method) Variant ofsetAllowedMethods(java.util.List<java.lang.String>)for adding one allowed method at a time.voidaddAllowedOrigin(String origin) Variant ofsetAllowedOrigins(java.util.List<java.lang.String>)for adding one origin at a time.voidaddAllowedOriginPattern(String originPattern) Variant ofsetAllowedOriginPatterns(java.util.List<java.lang.String>)for adding one origin at a time.voidaddExposedHeader(String exposedHeader) Variant ofsetExposedHeaders(java.util.List<java.lang.String>)for adding one exposed header at a time.By defaultCorsConfigurationdoes not permit any cross-origin requests and must be configured explicitly.checkHeaders(List<String> requestHeaders) Check the supplied request headers (or the headers listed in theAccess-Control-Request-Headersof a pre-flight request) against the configured allowed headers.checkHttpMethod(HttpMethod requestMethod) Check the HTTP request method (or the method from theAccess-Control-Request-Methodheader on a pre-flight request) against the configured allowed methods.checkOrigin(String origin) Check the origin of the request against the configured allowed origins.combine(CorsConfiguration other) Combine the non-null properties of the suppliedCorsConfigurationwith this one.Return the configuredallowCredentialsflag, ornullif none.Return the allowed actual request headers, ornullif none.Return the allowed HTTP methods, ornullin which case only"GET"and"HEAD"allowed.Return the configured origins patterns to allow, ornullif none.Return the configured origins to allow, ornullif none.Return the configuredallowPrivateNetworkflag, ornullif none.Return the configured response headers to expose, ornullif none.Return the configuredmaxAgevalue, ornullif none.voidsetAllowCredentials(Boolean allowCredentials) Whether user credentials are supported.voidsetAllowedHeaders(List<String> allowedHeaders) Set the list of headers that a pre-flight request can list as allowed for use during an actual request.voidsetAllowedMethods(List<String> allowedMethods) Set the HTTP methods to allow, e.g.setAllowedOriginPatterns(List<String> allowedOriginPatterns) Alternative tosetAllowedOrigins(java.util.List<java.lang.String>)that supports more flexible origins patterns with "*" anywhere in the host name in addition to port lists.voidsetAllowedOrigins(List<String> origins) A list of origins for which cross-origin requests are allowed where each value may be one of the following: a specific domain, e.g.voidsetAllowPrivateNetwork(Boolean allowPrivateNetwork) Whether private network access is supported for user-agents restricting such access by default.voidsetExposedHeaders(List<String> exposedHeaders) Set the list of response headers that an actual response might have and can be exposed to the client.voidConfigure how long, in seconds, the response from a pre-flight request can be cached by clients.voidConfigure how long, as a duration, the response from a pre-flight request can be cached by clients.voidValidate that whenallowCredentialsistrue,allowedOriginsdoes not contain the special value"*"since in that case the "Access-Control-Allow-Origin" cannot be set to"*".voidValidate that whenallowPrivateNetworkistrue,allowedOriginsdoes not contain the special value"*"since this is insecure.
-
Field Details
-
ALL
Wildcard representing all origins, methods, or headers.- See Also:
-
-
Constructor Details
-
CorsConfiguration
public CorsConfiguration()Construct a newCorsConfigurationinstance with no cross-origin requests allowed for any origin by default.- See Also:
-
CorsConfiguration
Construct a newCorsConfigurationinstance by copying all values from the suppliedCorsConfiguration.
-
-
Method Details
-
setAllowedOrigins
A list of origins for which cross-origin requests are allowed where each value may be one of the following:- a specific domain, e.g.
"https://domain1.com" - comma-delimited list of specific domains, e.g.
"https://a1.com,https://a2.com"; this is convenient when a value is resolved through a property placeholder, e.g."${origin}"; note that such placeholders must be resolved externally. - the CORS defined special value
"*"for all origins
For matched pre-flight and actual requests the
Access-Control-Allow-Originresponse header is set either to the matched domain value or to"*". Keep in mind however that the CORS spec does not allow"*"whenallowCredentialsis set totrue, and does not recommend"*"whenallowPrivateNetworkis set totrue. As a consequence, those combinations are rejected in favor of usingallowedOriginPatternsinstead.By default this is not set which means that no origins are allowed. However, an instance of this class is often initialized further, e.g. for
@CrossOrigin, viaapplyPermitDefaultValues(). - a specific domain, e.g.
-
getAllowedOrigins
Return the configured origins to allow, ornullif none. -
addAllowedOrigin
Variant ofsetAllowedOrigins(java.util.List<java.lang.String>)for adding one origin at a time. -
setAllowedOriginPatterns
Alternative tosetAllowedOrigins(java.util.List<java.lang.String>)that supports more flexible origins patterns with "*" anywhere in the host name in addition to port lists. Examples:- https://*.domain1.com -- domains ending with domain1.com
- https://*.domain1.com:[8080,8081] -- domains ending with domain1.com on port 8080 or port 8081
- https://*.domain1.com:[*] -- domains ending with domain1.com on any port, including the default port
- comma-delimited list of patters, e.g.
"https://*.a1.com,https://*.a2.com"; this is convenient when a value is resolved through a property placeholder, e.g."${origin}"; note that such placeholders must be resolved externally.
In contrast to
allowedOriginswhich only supports "*" and cannot be used withallowCredentialsorallowPrivateNetwork, when anallowedOriginPatternis matched, theAccess-Control-Allow-Originresponse header is set to the matched origin and not to"*"nor to the pattern. Therefore,allowedOriginPatternscan be used in combination withsetAllowCredentials(java.lang.Boolean)andsetAllowPrivateNetwork(java.lang.Boolean)set totrue.By default this is not set.
- Since:
- 5.3
-
getAllowedOriginPatterns
Return the configured origins patterns to allow, ornullif none.- Since:
- 5.3
-
addAllowedOriginPattern
Variant ofsetAllowedOriginPatterns(java.util.List<java.lang.String>)for adding one origin at a time.- Since:
- 5.3
-
setAllowedMethods
Set the HTTP methods to allow, e.g."GET","POST","PUT", etc. The special value"*"allows all methods.Access-Control-Allow-Methodsresponse header is set either to the configured method or to"*". Keep in mind however that the CORS spec does not allow"*"whenallowCredentialsis set totrue, that combination is handled by copying the method specified in the CORS preflight request.If not set, only
"GET"and"HEAD"are allowed.By default this is not set.
Note: CORS checks use values from "Forwarded" (RFC 7239), "X-Forwarded-Host", "X-Forwarded-Port", and "X-Forwarded-Proto" headers, if present, in order to reflect the client-originated address. Consider using the
ForwardedHeaderFilterin order to choose from a central place whether to extract and use, or to discard such headers. See the Spring Framework reference for more on this filter. -
getAllowedMethods
Return the allowed HTTP methods, ornullin which case only"GET"and"HEAD"allowed. -
addAllowedMethod
Variant ofsetAllowedMethods(java.util.List<java.lang.String>)for adding one allowed method at a time. -
addAllowedMethod
Variant ofsetAllowedMethods(java.util.List<java.lang.String>)for adding one allowed method at a time. -
setAllowedHeaders
Set the list of headers that a pre-flight request can list as allowed for use during an actual request. The special value"*"allows actual requests to send any header.Access-Control-Allow-Headersresponse header is set either to the configured list of headers or to"*". Keep in mind however that the CORS spec does not allow"*"whenallowCredentialsis set totrue, that combination is handled by copying the headers specified in the CORS preflight request.A header name is not required to be listed if it is one of:
Cache-Control,Content-Language,Expires,Last-Modified, orPragma.By default this is not set.
-
getAllowedHeaders
Return the allowed actual request headers, ornullif none. -
addAllowedHeader
Variant ofsetAllowedHeaders(List)for adding one allowed header at a time. -
setExposedHeaders
Set the list of response headers that an actual response might have and can be exposed to the client. The special value"*"allows all headers to be exposed.Access-Control-Expose-Headersresponse header is set either to the configured list of headers or to"*". While the CORS spec does not allow"*"whenAccess-Control-Allow-Credentialsis set totrue, most browsers support it and the response headers are not all available during the CORS processing, so as a consequence"*"is the header value used when specified regardless of the value of the `allowCredentials` property.A header name is not required to be listed if it is one of:
Cache-Control,Content-Language,Expires,Last-Modified, orPragma.By default this is not set.
-
getExposedHeaders
Return the configured response headers to expose, ornullif none. -
addExposedHeader
Variant ofsetExposedHeaders(java.util.List<java.lang.String>)for adding one exposed header at a time. -
setAllowCredentials
Whether user credentials are supported.Setting this property has an impact on how
origins,originPatterns,allowedMethodsandallowedHeadersare processed, see related API documentation for more details.NOTE: Be aware that this option establishes a high level of trust with the configured domains and also increases the surface attack of the web application by exposing sensitive user-specific information such as cookies and CSRF tokens.
By default this is not set (i.e. user credentials are not supported).
-
getAllowCredentials
Return the configuredallowCredentialsflag, ornullif none.- See Also:
-
setAllowPrivateNetwork
Whether private network access is supported for user-agents restricting such access by default.Private network requests are requests whose target server's IP address is more private than that from which the request initiator was fetched. For example, a request from a public website (https://example.com) to a private website (https://router.local), or a request from a private website to localhost.
Setting this property has an impact on how
originsandoriginPatternsare processed, see related API documentation for more details.By default this is not set (i.e. private network access is not supported).
- Since:
- 5.3.32
- See Also:
-
getAllowPrivateNetwork
Return the configuredallowPrivateNetworkflag, ornullif none.- Since:
- 5.3.32
- See Also:
-
setMaxAge
Configure how long, as a duration, the response from a pre-flight request can be cached by clients.- Since:
- 5.2
- See Also:
-
setMaxAge
Configure how long, in seconds, the response from a pre-flight request can be cached by clients.By default this is not set.
-
getMaxAge
Return the configuredmaxAgevalue, ornullif none.- See Also:
-
applyPermitDefaultValues
By defaultCorsConfigurationdoes not permit any cross-origin requests and must be configured explicitly. Use this method to switch to defaults that permit all cross-origin requests for GET, HEAD, and POST, but not overriding any values that have already been set.The following defaults are applied for values that are not set:
- Allow all origins with the special value
"*"defined in the CORS spec. This is set only if neitheroriginsnororiginPatternsare already set. - Allow "simple" methods
GET,HEADandPOST. - Allow all headers.
- Set max age to 1800 seconds (30 minutes).
- Allow all origins with the special value
-
validateAllowCredentials
public void validateAllowCredentials()Validate that whenallowCredentialsistrue,allowedOriginsdoes not contain the special value"*"since in that case the "Access-Control-Allow-Origin" cannot be set to"*".- Throws:
IllegalArgumentException- if the validation fails- Since:
- 5.3
-
validateAllowPrivateNetwork
public void validateAllowPrivateNetwork()Validate that whenallowPrivateNetworkistrue,allowedOriginsdoes not contain the special value"*"since this is insecure.- Throws:
IllegalArgumentException- if the validation fails- Since:
- 5.3.32
-
combine
Combine the non-null properties of the suppliedCorsConfigurationwith this one.When combining single values like
allowCredentialsormaxAge,thisproperties are overridden by non-nullotherproperties if any.Combining lists like
allowedOrigins,allowedMethods,allowedHeadersorexposedHeadersis done in an additive way. For example, combining["GET", "POST"]with["PATCH"]results in["GET", "POST", "PATCH"]. However, combining["GET", "POST"]with["*"]results in["*"]. Note also that default permit values set byapplyPermitDefaultValues()are overridden by any explicitly defined values.- Returns:
- the combined
CorsConfiguration, orthisconfiguration if the supplied configuration isnull
-
checkOrigin
Check the origin of the request against the configured allowed origins.- Parameters:
origin- the origin to check- Returns:
- the origin to use for the response, or
nullwhich means the request origin is not allowed
-
checkHttpMethod
Check the HTTP request method (or the method from theAccess-Control-Request-Methodheader on a pre-flight request) against the configured allowed methods.- Parameters:
requestMethod- the HTTP request method to check- Returns:
- the list of HTTP methods to list in the response of a pre-flight
request, or
nullif the suppliedrequestMethodis not allowed
-
checkHeaders
Check the supplied request headers (or the headers listed in theAccess-Control-Request-Headersof a pre-flight request) against the configured allowed headers.- Parameters:
requestHeaders- the request headers to check- Returns:
- the list of allowed headers to list in the response of a pre-flight
request, or
nullif none of the supplied request headers is allowed
-