Top Description Inners Fields Constructors Methods
org.springframework.web.cors

public Class CorsConfiguration

extends Object
Class Inheritance
Imports
java.time.Duration, java.util.ArrayList, .Collections, .LinkedHashSet, .List, .Set, java.util.function.Consumer, java.util.regex.Matcher, .Pattern, org.springframework.http.HttpMethod, org.springframework.lang.Nullable, org.springframework.util.CollectionUtils, .ObjectUtils, .StringUtils

A container for CORS configuration along with methods to check against the actual origin, HTTP methods, and headers of a given request.

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.

Authors
Sebastien Deleuze, Rossen Stoyanchev, Juergen Hoeller, Sam Brannen, Ruslan Akhundov
Since
4.2
See Also
CORS spec

Nested and Inner Type Summary

Modifier and TypeClass and Description
private static class
CorsConfiguration.OriginPattern

Contains both the user-declared pattern (e.g. "https://*.domain.com") and the regex Pattern derived from it.

Field Summary

Modifier and TypeField and Description
public static final String
ALL

Wildcard representing all origins, methods, or headers.

private static final List<String>
private static final CorsConfiguration.OriginPattern
private static final List<CorsConfiguration.OriginPattern>
private Boolean
private List<String>
private List<String>
private List<CorsConfiguration.OriginPattern>
private List<String>
private Boolean
private static final List<HttpMethod>
private static final List<String>
private static final List<String>
private List<String>
private Long
private List<HttpMethod>

Constructor Summary

AccessConstructor and Description
public
CorsConfiguration()

Construct a new CorsConfiguration instance with no cross-origin requests allowed for any origin by default.

public
CorsConfiguration(CorsConfiguration other)

Construct a new CorsConfiguration instance by copying all values from the supplied CorsConfiguration.

Method Summary

Modifier and TypeMethod and Description
public void
addAllowedHeader(String allowedHeader)

Variant of setAllowedHeaders(List) for adding one allowed header at a time.

public void
addAllowedMethod(HttpMethod method)

Variant of setAllowedMethods for adding one allowed method at a time.

public void
addAllowedMethod(String method)

Variant of setAllowedMethods for adding one allowed method at a time.

public void
addAllowedOrigin(String origin)

Variant of setAllowedOrigins for adding one origin at a time.

public void
addAllowedOriginPattern(String originPattern)

Variant of setAllowedOriginPatterns for adding one origin at a time.

public void
addExposedHeader(String exposedHeader)

Variant of setExposedHeaders for adding one exposed header at a time.

public CorsConfiguration
applyPermitDefaultValues()

By default CorsConfiguration does not permit any cross-origin requests and must be configured explicitly.

public List<String>

Returns:

the list of allowed headers to list in the response of a pre-flight request, or null if none of the supplied request headers is allowed
checkHeaders
(List<String>
the request headers to check
requestHeaders
)

Check the supplied request headers (or the headers listed in the Access-Control-Request-Headers of a pre-flight request) against the configured allowed headers.

public List<HttpMethod>

Returns:

the list of HTTP methods to list in the response of a pre-flight request, or null if the supplied requestMethod is not allowed
checkHttpMethod
(HttpMethod
the HTTP request method to check
requestMethod
)

Check the HTTP request method (or the method from the Access-Control-Request-Method header on a pre-flight request) against the configured allowed methods.

public String

Returns:

the origin to use for the response, or null which means the request origin is not allowed
checkOrigin
(String
the origin to check
origin
)

Check the origin of the request against the configured allowed origins.

public CorsConfiguration

Returns:

the combined CorsConfiguration, or this configuration if the supplied configuration is null
combine
(CorsConfiguration other)

Combine the non-null properties of the supplied CorsConfiguration with this one.

private List<String>
combine(List<String> source, List<String> other)

private List<CorsConfiguration.OriginPattern>
public Boolean
getAllowCredentials()

Return the configured allowCredentials flag, or null if none.

public List<String>
getAllowedHeaders()

Return the allowed actual request headers, or null if none.

public List<String>
getAllowedMethods()

Return the allowed HTTP methods, or null in which case only "GET" and "HEAD" allowed.

public List<String>
getAllowedOriginPatterns()

Return the configured origins patterns to allow, or null if none.

public List<String>
getAllowedOrigins()

Return the configured origins to allow, or null if none.

public Boolean
getAllowPrivateNetwork()

Return the configured allowPrivateNetwork flag, or null if none.

public List<String>
getExposedHeaders()

Return the configured response headers to expose, or null if none.

public Long
getMaxAge()

Return the configured maxAge value, or null if none.

private static void
parseCommaDelimitedOrigin(String rawValue, Consumer<String> valueConsumer)

public void
setAllowCredentials(Boolean allowCredentials)

Whether user credentials are supported.

public void
setAllowedHeaders(List<String> allowedHeaders)

Set the list of headers that a pre-flight request can list as allowed for use during an actual request.

public void
setAllowedMethods(List<String> allowedMethods)

Set the HTTP methods to allow, e.g. "GET", "POST", "PUT", etc. The special value "*" allows all methods.

public CorsConfiguration
setAllowedOriginPatterns(List<String> allowedOriginPatterns)

Alternative to setAllowedOrigins that supports more flexible origins patterns with "*" anywhere in the host name in addition to port lists.

public void
setAllowedOrigins(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. "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
public void
setAllowPrivateNetwork(Boolean allowPrivateNetwork)

Whether private network access is supported for user-agents restricting such access by default.

public void
setExposedHeaders(List<String> exposedHeaders)

Set the list of response headers that an actual response might have and can be exposed to the client.

public void
setMaxAge(Duration maxAge)

Configure how long, as a duration, the response from a pre-flight request can be cached by clients.

public void
setMaxAge(Long maxAge)

Configure how long, in seconds, the response from a pre-flight request can be cached by clients.

private String
public void
validateAllowCredentials()

Validate that when allowCredentials is true, allowedOrigins does not contain the special value "*" since in that case the "Access-Control-Allow-Origin" cannot be set to "*".

public void
validateAllowPrivateNetwork()

Validate that when allowPrivateNetwork is true, allowedOrigins does not contain the special value "*" since this is insecure.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

ALLback to summary
public static final String ALL

Wildcard representing all origins, methods, or headers.

ALL_LISTback to summary
private static final List<String> ALL_LIST
ALL_PATTERNback to summary
private static final CorsConfiguration.OriginPattern ALL_PATTERN
ALL_PATTERN_LISTback to summary
private static final List<CorsConfiguration.OriginPattern> ALL_PATTERN_LIST
allowCredentialsback to summary
private Boolean allowCredentials
Annotations
@Nullable
allowedHeadersback to summary
private List<String> allowedHeaders
Annotations
@Nullable
allowedMethodsback to summary
private List<String> allowedMethods
Annotations
@Nullable
allowedOriginPatternsback to summary
private List<CorsConfiguration.OriginPattern> allowedOriginPatterns
Annotations
@Nullable
allowedOriginsback to summary
private List<String> allowedOrigins
Annotations
@Nullable
allowPrivateNetworkback to summary
private Boolean allowPrivateNetwork
Annotations
@Nullable
DEFAULT_METHODSback to summary
private static final List<HttpMethod> DEFAULT_METHODS
DEFAULT_PERMIT_ALLback to summary
private static final List<String> DEFAULT_PERMIT_ALL
DEFAULT_PERMIT_METHODSback to summary
private static final List<String> DEFAULT_PERMIT_METHODS
exposedHeadersback to summary
private List<String> exposedHeaders
Annotations
@Nullable
maxAgeback to summary
private Long maxAge
Annotations
@Nullable
resolvedMethodsback to summary
private List<HttpMethod> resolvedMethods
Annotations
@Nullable

Constructor Detail

CorsConfigurationback to summary
public CorsConfiguration()

Construct a new CorsConfiguration instance with no cross-origin requests allowed for any origin by default.

See Also
applyPermitDefaultValues()
CorsConfigurationback to summary
public CorsConfiguration(CorsConfiguration other)

Construct a new CorsConfiguration instance by copying all values from the supplied CorsConfiguration.

Method Detail

addAllowedHeaderback to summary
public void addAllowedHeader(String allowedHeader)

Variant of setAllowedHeaders(List) for adding one allowed header at a time.

addAllowedMethodback to summary
public void addAllowedMethod(HttpMethod method)

Variant of setAllowedMethods for adding one allowed method at a time.

addAllowedMethodback to summary
public void addAllowedMethod(String method)

Variant of setAllowedMethods for adding one allowed method at a time.

addAllowedOriginback to summary
public void addAllowedOrigin(String origin)

Variant of setAllowedOrigins for adding one origin at a time.

addAllowedOriginPatternback to summary
public void addAllowedOriginPattern(String originPattern)

Variant of setAllowedOriginPatterns for adding one origin at a time.

Since
5.3
addExposedHeaderback to summary
public void addExposedHeader(String exposedHeader)

Variant of setExposedHeaders for adding one exposed header at a time.

applyPermitDefaultValuesback to summary
public CorsConfiguration applyPermitDefaultValues()

By default CorsConfiguration does 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 neither origins nor originPatterns are already set.
  • Allow "simple" methods GET, HEAD and POST.
  • Allow all headers.
  • Set max age to 1800 seconds (30 minutes).
checkHeadersback to summary
public List<String> checkHeaders(List<String> requestHeaders)

Check the supplied request headers (or the headers listed in the Access-Control-Request-Headers of a pre-flight request) against the configured allowed headers.

Parameters
requestHeaders:List<String>

the request headers to check

Returns:List<String>

the list of allowed headers to list in the response of a pre-flight request, or null if none of the supplied request headers is allowed

Annotations
@Nullable
checkHttpMethodback to summary
public List<HttpMethod> checkHttpMethod(HttpMethod requestMethod)

Check the HTTP request method (or the method from the Access-Control-Request-Method header on a pre-flight request) against the configured allowed methods.

Parameters
requestMethod:HttpMethod

the HTTP request method to check

Returns:List<HttpMethod>

the list of HTTP methods to list in the response of a pre-flight request, or null if the supplied requestMethod is not allowed

Annotations
@Nullable
checkOriginback to summary
public String checkOrigin(String origin)

Check the origin of the request against the configured allowed origins.

Parameters
origin:String

the origin to check

Returns:String

the origin to use for the response, or null which means the request origin is not allowed

Annotations
@Nullable
combineback to summary
public CorsConfiguration combine(CorsConfiguration other)

Combine the non-null properties of the supplied CorsConfiguration with this one.

When combining single values like allowCredentials or maxAge, this properties are overridden by non-null other properties if any.

Combining lists like allowedOrigins, allowedMethods, allowedHeaders or exposedHeaders is 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 by CorsConfiguration#applyPermitDefaultValues() are overridden by any explicitly defined values.

Returns:CorsConfiguration

the combined CorsConfiguration, or this configuration if the supplied configuration is null

combineback to summary
private List<String> combine(List<String> source, List<String> other)
combinePatternsback to summary
private List<CorsConfiguration.OriginPattern> combinePatterns(List<CorsConfiguration.OriginPattern> source, List<CorsConfiguration.OriginPattern> other)
getAllowCredentialsback to summary
public Boolean getAllowCredentials()

Return the configured allowCredentials flag, or null if none.

Annotations
@Nullable
See Also
setAllowCredentials(Boolean)
getAllowedHeadersback to summary
public List<String> getAllowedHeaders()

Return the allowed actual request headers, or null if none.

Annotations
@Nullable
See Also
addAllowedHeader(String), setAllowedHeaders(List)
getAllowedMethodsback to summary
public List<String> getAllowedMethods()

Return the allowed HTTP methods, or null in which case only "GET" and "HEAD" allowed.

Annotations
@Nullable
See Also
setAllowedMethods(List), addAllowedMethod(HttpMethod), addAllowedMethod(String)
getAllowedOriginPatternsback to summary
public List<String> getAllowedOriginPatterns()

Return the configured origins patterns to allow, or null if none.

Annotations
@Nullable
Since
5.3
getAllowedOriginsback to summary
public List<String> getAllowedOrigins()

Return the configured origins to allow, or null if none.

Annotations
@Nullable
getAllowPrivateNetworkback to summary
public Boolean getAllowPrivateNetwork()

Return the configured allowPrivateNetwork flag, or null if none.

Annotations
@Nullable
Since
5.3.32
See Also
setAllowPrivateNetwork(Boolean)
getExposedHeadersback to summary
public List<String> getExposedHeaders()

Return the configured response headers to expose, or null if none.

Annotations
@Nullable
See Also
addExposedHeader(String), setExposedHeaders(List)
getMaxAgeback to summary
public Long getMaxAge()

Return the configured maxAge value, or null if none.

Annotations
@Nullable
See Also
setMaxAge(Long)
parseCommaDelimitedOriginback to summary
private static void parseCommaDelimitedOrigin(String rawValue, Consumer<String> valueConsumer)
setAllowCredentialsback to summary
public void setAllowCredentials(Boolean allowCredentials)

Whether user credentials are supported.

Setting this property has an impact on how origins, originPatterns, allowedMethods and allowedHeaders are 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).

setAllowedHeadersback to summary
public void setAllowedHeaders(List<String> allowedHeaders)

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-Headers response header is set either to the configured list of headers or to "*". Keep in mind however that the CORS spec does not allow "*" when allowCredentials is set to true, 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, or Pragma.

By default this is not set.

setAllowedMethodsback to summary
public void setAllowedMethods(List<String> allowedMethods)

Set the HTTP methods to allow, e.g. "GET", "POST", "PUT", etc. The special value "*" allows all methods.

Access-Control-Allow-Methods response header is set either to the configured method or to "*". Keep in mind however that the CORS spec does not allow "*" when allowCredentials is set to true, 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 ForwardedHeaderFilter in 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.

setAllowedOriginPatternsback to summary
public CorsConfiguration setAllowedOriginPatterns(List<String> allowedOriginPatterns)

Alternative to setAllowedOrigins 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 allowedOrigins which only supports "*" and cannot be used with allowCredentials or allowPrivateNetwork, when an allowedOriginPattern is matched, the Access-Control-Allow-Origin response header is set to the matched origin and not to "*" nor to the pattern. Therefore, allowedOriginPatterns can be used in combination with setAllowCredentials and setAllowPrivateNetwork set to true.

By default this is not set.

Since
5.3
setAllowedOriginsback to summary
public void setAllowedOrigins(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. "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-Origin response header is set either to the matched domain value or to "*". Keep in mind however that the CORS spec does not allow "*" when allowCredentials is set to true, and does not recommend "*" when allowPrivateNetwork is set to true. As a consequence, those combinations are rejected in favor of using allowedOriginPatterns instead.

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, via applyPermitDefaultValues().

setAllowPrivateNetworkback to summary
public void setAllowPrivateNetwork(Boolean allowPrivateNetwork)

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 origins and originPatterns are 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
Private network access specifications
setExposedHeadersback to summary
public void setExposedHeaders(List<String> exposedHeaders)

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-Headers response header is set either to the configured list of headers or to "*". While the CORS spec does not allow "*" when Access-Control-Allow-Credentials is set to true, 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, or Pragma.

By default this is not set.

setMaxAgeback to summary
public void setMaxAge(Duration maxAge)

Configure how long, as a duration, the response from a pre-flight request can be cached by clients.

Since
5.2
See Also
setMaxAge(Long)
setMaxAgeback to summary
public void setMaxAge(Long maxAge)

Configure how long, in seconds, the response from a pre-flight request can be cached by clients.

By default this is not set.

trimTrailingSlashback to summary
private String trimTrailingSlash(String origin)
validateAllowCredentialsback to summary
public void validateAllowCredentials()

Validate that when allowCredentials is true, allowedOrigins does not contain the special value "*" since in that case the "Access-Control-Allow-Origin" cannot be set to "*".

Exceptions
IllegalArgumentException:
if the validation fails
Since
5.3
validateAllowPrivateNetworkback to summary
public void validateAllowPrivateNetwork()

Validate that when allowPrivateNetwork is true, allowedOrigins does not contain the special value "*" since this is insecure.

Exceptions
IllegalArgumentException:
if the validation fails
Since
5.3.32
org.springframework.web.cors back to summary

private Class CorsConfiguration.OriginPattern

extends Object
Class Inheritance

Contains both the user-declared pattern (e.g. "https://*.domain.com") and the regex Pattern derived from it.

Field Summary

Modifier and TypeField and Description
private final String
private final Pattern
private static final Pattern

Constructor Summary

AccessConstructor and Description
pack-priv
OriginPattern(String declaredPattern)

Method Summary

Modifier and TypeMethod and Description
public boolean
equals(Object
the reference object with which to compare.
other
)

Overrides java.lang.Object.equals.

Indicates whether some other object is "equal to" this one.
public String
public Pattern
public int
hashCode()

Overrides java.lang.Object.hashCode.

Returns a hash code value for the object.
private static Pattern
initPattern(String patternValue)

public String
toString()

Overrides java.lang.Object.toString.

Returns a string representation of the object.
Inherited from java.lang.Object:
clonefinalizegetClassnotifynotifyAllwaitwaitwait

Field Detail

declaredPatternback to summary
private final String declaredPattern
patternback to summary
private final Pattern pattern
PORTS_PATTERNback to summary
private static final Pattern PORTS_PATTERN

Constructor Detail

OriginPatternback to summary
pack-priv OriginPattern(String declaredPattern)

Method Detail

equalsback to summary
public boolean equals(Object other)

Overrides java.lang.Object.equals.

Doc from java.lang.Object.equals.

Indicates whether some other object is "equal to" this one.

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

An equivalence relation partitions the elements it operates on into equivalence classes; all the members of an equivalence class are equal to each other. Members of an equivalence class are substitutable for each other, at least for some purposes.

Parameters
other:Object

the reference object with which to compare.

Returns:boolean

true if this object is the same as the obj argument; false otherwise.

Annotations
@Override
getDeclaredPatternback to summary
public String getDeclaredPattern()
getPatternback to summary
public Pattern getPattern()
hashCodeback to summary
public int hashCode()

Overrides java.lang.Object.hashCode.

Doc from java.lang.Object.hashCode.

Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by java.util.HashMap.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
Returns:int

a hash code value for this object.

Annotations
@Override
initPatternback to summary
private static Pattern initPattern(String patternValue)
toStringback to summary
public String toString()

Overrides java.lang.Object.toString.

Doc from java.lang.Object.toString.

Returns a string representation of the object.

Returns:String

a string representation of the object.

Annotations
@Override