Package org.apache.catalina.filters

## Class CorsFilter

- java.lang.Object
- - org.apache.catalina.filters.CorsFilter

All Implemented Interfaces:
  `Filter`

    public class CorsFilter
    extends java.lang.Object
    implements Filter

A `Filter` that enable client-side cross-origin requests by implementing W3C's CORS (Cross-Origin Resource Sharing) specification for resources. Each `HttpServletRequest` request is inspected as per specification, and appropriate response headers are added to `HttpServletResponse`.

By default, it also sets following request attributes, that help to determine the nature of the request downstream.

- cors.isCorsRequest: Flag to determine if the request is a CORS request. Set to `true` if a CORS request; `false` otherwise.
- cors.request.origin: The Origin URL, i.e. the URL of the page from where the request is originated.
- cors.request.type: Type of request. Possible values:
  - SIMPLE: A request which is not preceded by a pre-flight request.
  - ACTUAL: A request which is preceded by a pre-flight request.
  - PRE_FLIGHT: A pre-flight request.
  - NOT_CORS: A normal same-origin request.
  - INVALID_CORS: A cross-origin request which is invalid.
- cors.request.headers: Request headers sent as 'Access-Control-Request-Headers' header, for pre-flight request.

If you extend this class and override one or more of the getXxx() methods, consider whether you also need to override `doFilter(ServletRequest, ServletResponse, FilterChain)` and add appropriate locking so that the `doFilter()` method executes with a consistent configuration.

See Also:
  CORS specification

### Nested Class Summary

Nested Classes
`protected static class` `CorsFilter.CORSRequestType` Enumerates varies types of CORS requests.

### Field Summary

Fields
`static java.lang.String` `DEFAULT_ALLOWED_HTTP_HEADERS` By default, following headers are supported: Origin,Accept,X-Requested-With, Content-Type, Access-Control-Request-Method, and Access-Control-Request-Headers.
`static java.lang.String` `DEFAULT_ALLOWED_HTTP_METHODS` By default, following methods are supported: GET, POST, HEAD and OPTIONS.
`static java.lang.String` `DEFAULT_ALLOWED_ORIGINS` By default, no origins are allowed to make requests.
`static java.lang.String` `DEFAULT_DECORATE_REQUEST` By default, request is decorated with CORS attributes.
`static java.lang.String` `DEFAULT_EXPOSED_HEADERS` By default, none of the headers are exposed in response.
`static java.lang.String` `DEFAULT_PREFLIGHT_MAXAGE` By default, time duration to cache pre-flight response is 30 mins.
`static java.lang.String` `DEFAULT_SUPPORTS_CREDENTIALS` By default, support credentials is disabled.
`static java.lang.String` `HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST` Boolean value, suggesting if the request is a CORS request or not.
`static java.lang.String` `HTTP_REQUEST_ATTRIBUTE_ORIGIN` Attribute that contains the origin of the request.
`static java.lang.String` `HTTP_REQUEST_ATTRIBUTE_PREFIX` The prefix to a CORS request attribute.
`static java.lang.String` `HTTP_REQUEST_ATTRIBUTE_REQUEST_HEADERS` Request headers sent as 'Access-Control-Request-Headers' header, for pre-flight request.
`static java.lang.String` `HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE` Type of CORS request, of type `CorsFilter.CORSRequestType`.
`static java.lang.String` `PARAM_CORS_ALLOWED_HEADERS` Key to retrieve allowed headers from `FilterConfig`.
`static java.lang.String` `PARAM_CORS_ALLOWED_METHODS` Key to retrieve allowed methods from `FilterConfig`.
`static java.lang.String` `PARAM_CORS_ALLOWED_ORIGINS` Key to retrieve allowed origins from `FilterConfig`.
`static java.lang.String` `PARAM_CORS_EXPOSED_HEADERS` Key to retrieve exposed headers from `FilterConfig`.
`static java.lang.String` `PARAM_CORS_PREFLIGHT_MAXAGE` Key to retrieve preflight max age from `FilterConfig`.
`static java.lang.String` `PARAM_CORS_REQUEST_DECORATE` Key to determine if request should be decorated.
`static java.lang.String` `PARAM_CORS_SUPPORT_CREDENTIALS` Key to retrieve support credentials from `FilterConfig`.
`static java.lang.String` `REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS` The Access-Control-Request-Headers header indicates which headers will be used in the actual request as part of the preflight request.
`static java.lang.String` `REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD` The Access-Control-Request-Method header indicates which method will be used in the actual request as part of the preflight request.
`static java.lang.String` `REQUEST_HEADER_ORIGIN` The Origin header indicates where the cross-origin request or preflight request originates from.
`static java.lang.String` `REQUEST_HEADER_VARY` Deprecated. Unused.
`static java.lang.String` `RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS` The Access-Control-Allow-Credentials header indicates whether the response to request can be exposed when the omit credentials flag is unset.
`static java.lang.String` `RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_HEADERS` The Access-Control-Allow-Headers header indicates, as part of the response to a preflight request, which header field names can be used during the actual request.
`static java.lang.String` `RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_METHODS` The Access-Control-Allow-Methods header indicates, as part of the response to a preflight request, which methods can be used during the actual request.
`static java.lang.String` `RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN` The Access-Control-Allow-Origin header indicates whether a resource can be shared based by returning the value of the Origin request header in the response.
`static java.lang.String` `RESPONSE_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS` The Access-Control-Expose-Headers header indicates which headers are safe to expose to the API of a CORS API specification
`static java.lang.String` `RESPONSE_HEADER_ACCESS_CONTROL_MAX_AGE` The Access-Control-Max-Age header indicates how long the results of a preflight request can be cached in a preflight result cache.
`static java.util.Collection<java.lang.String>` `SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES` `Collection` of media type values for the Content-Type header that will be treated as 'simple'.

### Constructor Summary

Constructors
`CorsFilter()`

### Method Summary

All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods
`protected CorsFilter.CORSRequestType` `checkRequestType​(HttpServletRequest request)` Determines the request type.
`protected static void` `decorateCORSProperties​(HttpServletRequest request, CorsFilter.CORSRequestType corsRequestType)` Decorates the `HttpServletRequest`, with CORS attributes.
`void` `destroy()` Called by the web container to indicate to a filter that it is being taken out of service.
`void` `doFilter​(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)` The `doFilter` method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain.
`java.util.Collection<java.lang.String>` `getAllowedHttpHeaders()` Returns a `Set` of headers support by resource.
`java.util.Collection<java.lang.String>` `getAllowedHttpMethods()` Returns a `Set` of HTTP methods that are allowed to make requests.
`java.util.Collection<java.lang.String>` `getAllowedOrigins()` Returns the `Set` of allowed origins that are allowed to make requests.
`java.util.Collection<java.lang.String>` `getExposedHeaders()` Obtain the headers to expose.
`long` `getPreflightMaxAge()` Returns the preflight response cache time in seconds.
`protected void` `handlePreflightCORS​(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)` Handles CORS pre-flight request.
`protected void` `handleSimpleCORS​(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)` Handles a CORS request of type `CorsFilter.CORSRequestType`.SIMPLE.
`void` `init​(FilterConfig filterConfig)` Called by the web container to indicate to a filter that it is being placed into service.
`boolean` `isAnyOriginAllowed()` Determines if any origin is allowed to make CORS request.
`boolean` `isDecorateRequest()` Should CORS specific attributes be added to the request.
`boolean` `isSupportsCredentials()` Determines is supports credentials is enabled.
`protected static boolean` `isValidOrigin​(java.lang.String origin)` Deprecated. This will be removed in Tomcat 10 Use `RequestUtil.isValidOrigin(String)`
`protected static java.lang.String` `join​(java.util.Collection<java.lang.String> elements, java.lang.String joinSeparator)` Joins elements of `Set` into a string, where each element is separated by the provided separator.

### Methods inherited from class java.lang.Object

`clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

### Field Detail

#### RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN

    public static final java.lang.String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN

The Access-Control-Allow-Origin header indicates whether a resource can be shared based by returning the value of the Origin request header in the response.

See Also:
  Constant Field Values

#### RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS

    public static final java.lang.String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS

The Access-Control-Allow-Credentials header indicates whether the response to request can be exposed when the omit credentials flag is unset. When part of the response to a preflight request it indicates that the actual request can include user credentials.

See Also:
  Constant Field Values

#### RESPONSE_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS

    public static final java.lang.String RESPONSE_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS

The Access-Control-Expose-Headers header indicates which headers are safe to expose to the API of a CORS API specification

See Also:
  Constant Field Values

#### RESPONSE_HEADER_ACCESS_CONTROL_MAX_AGE

    public static final java.lang.String RESPONSE_HEADER_ACCESS_CONTROL_MAX_AGE

The Access-Control-Max-Age header indicates how long the results of a preflight request can be cached in a preflight result cache.

See Also:
  Constant Field Values

#### RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_METHODS

    public static final java.lang.String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_METHODS

The Access-Control-Allow-Methods header indicates, as part of the response to a preflight request, which methods can be used during the actual request.

See Also:
  Constant Field Values

#### RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_HEADERS

    public static final java.lang.String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_HEADERS

The Access-Control-Allow-Headers header indicates, as part of the response to a preflight request, which header field names can be used during the actual request.

See Also:
  Constant Field Values

#### REQUEST_HEADER_VARY

    @Deprecated
    public static final java.lang.String REQUEST_HEADER_VARY

Deprecated.
Unused. Will be removed in Tomcat 10
The Vary header indicates allows disabling proxy caching by indicating the the response depends on the origin.

See Also:
  Constant Field Values

#### REQUEST_HEADER_ORIGIN

    public static final java.lang.String REQUEST_HEADER_ORIGIN

The Origin header indicates where the cross-origin request or preflight request originates from.

See Also:
  Constant Field Values

#### REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD

    public static final java.lang.String REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD

The Access-Control-Request-Method header indicates which method will be used in the actual request as part of the preflight request.

See Also:
  Constant Field Values

#### REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS

    public static final java.lang.String REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS

The Access-Control-Request-Headers header indicates which headers will be used in the actual request as part of the preflight request.

See Also:
  Constant Field Values

#### HTTP_REQUEST_ATTRIBUTE_PREFIX

    public static final java.lang.String HTTP_REQUEST_ATTRIBUTE_PREFIX

The prefix to a CORS request attribute.

See Also:
  Constant Field Values

#### HTTP_REQUEST_ATTRIBUTE_ORIGIN

    public static final java.lang.String HTTP_REQUEST_ATTRIBUTE_ORIGIN

Attribute that contains the origin of the request.

See Also:
  Constant Field Values

#### HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST

    public static final java.lang.String HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST

Boolean value, suggesting if the request is a CORS request or not.

See Also:
  Constant Field Values

#### HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE

    public static final java.lang.String HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE

Type of CORS request, of type `CorsFilter.CORSRequestType`.

See Also:
  Constant Field Values

#### HTTP_REQUEST_ATTRIBUTE_REQUEST_HEADERS

    public static final java.lang.String HTTP_REQUEST_ATTRIBUTE_REQUEST_HEADERS

Request headers sent as 'Access-Control-Request-Headers' header, for pre-flight request.

See Also:
  Constant Field Values

#### SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES

    public static final java.util.Collection<java.lang.String> SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES

`Collection` of media type values for the Content-Type header that will be treated as 'simple'. Note media-type values are compared ignoring parameters and in a case-insensitive manner.

See Also:
  http://www.w3.org/TR/cors/#terminology

#### DEFAULT_ALLOWED_ORIGINS

    public static final java.lang.String DEFAULT_ALLOWED_ORIGINS

By default, no origins are allowed to make requests.

See Also:
  Constant Field Values

#### DEFAULT_ALLOWED_HTTP_METHODS

    public static final java.lang.String DEFAULT_ALLOWED_HTTP_METHODS

By default, following methods are supported: GET, POST, HEAD and OPTIONS.

See Also:
  Constant Field Values

#### DEFAULT_PREFLIGHT_MAXAGE

    public static final java.lang.String DEFAULT_PREFLIGHT_MAXAGE

By default, time duration to cache pre-flight response is 30 mins.

See Also:
  Constant Field Values

#### DEFAULT_SUPPORTS_CREDENTIALS

    public static final java.lang.String DEFAULT_SUPPORTS_CREDENTIALS

By default, support credentials is disabled.

See Also:
  Constant Field Values

#### DEFAULT_ALLOWED_HTTP_HEADERS

    public static final java.lang.String DEFAULT_ALLOWED_HTTP_HEADERS

By default, following headers are supported: Origin,Accept,X-Requested-With, Content-Type, Access-Control-Request-Method, and Access-Control-Request-Headers.

See Also:
  Constant Field Values

#### DEFAULT_EXPOSED_HEADERS

    public static final java.lang.String DEFAULT_EXPOSED_HEADERS

By default, none of the headers are exposed in response.

See Also:
  Constant Field Values

#### DEFAULT_DECORATE_REQUEST

    public static final java.lang.String DEFAULT_DECORATE_REQUEST

By default, request is decorated with CORS attributes.

See Also:
  Constant Field Values

#### PARAM_CORS_ALLOWED_ORIGINS

    public static final java.lang.String PARAM_CORS_ALLOWED_ORIGINS

Key to retrieve allowed origins from `FilterConfig`.

See Also:
  Constant Field Values

#### PARAM_CORS_SUPPORT_CREDENTIALS

    public static final java.lang.String PARAM_CORS_SUPPORT_CREDENTIALS

Key to retrieve support credentials from `FilterConfig`.

See Also:
  Constant Field Values

#### PARAM_CORS_EXPOSED_HEADERS

    public static final java.lang.String PARAM_CORS_EXPOSED_HEADERS

Key to retrieve exposed headers from `FilterConfig`.

See Also:
  Constant Field Values

#### PARAM_CORS_ALLOWED_HEADERS

    public static final java.lang.String PARAM_CORS_ALLOWED_HEADERS

Key to retrieve allowed headers from `FilterConfig`.

See Also:
  Constant Field Values

#### PARAM_CORS_ALLOWED_METHODS

    public static final java.lang.String PARAM_CORS_ALLOWED_METHODS

Key to retrieve allowed methods from `FilterConfig`.

See Also:
  Constant Field Values

#### PARAM_CORS_PREFLIGHT_MAXAGE

    public static final java.lang.String PARAM_CORS_PREFLIGHT_MAXAGE

Key to retrieve preflight max age from `FilterConfig`.

See Also:
  Constant Field Values

#### PARAM_CORS_REQUEST_DECORATE

    public static final java.lang.String PARAM_CORS_REQUEST_DECORATE

Key to determine if request should be decorated.

See Also:
  Constant Field Values

### Constructor Detail

#### CorsFilter

    public CorsFilter()

### Method Detail

#### doFilter

    public void doFilter​(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain)
                  throws java.io.IOException,
                         ServletException

Description copied from interface: `javax.servlet.Filter`
The `doFilter` method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. The FilterChain passed in to this method allows the Filter to pass on the request and response to the next entity in the chain.

A typical implementation of this method would follow the following pattern:-
1. Examine the request
2. Optionally wrap the request object with a custom implementation to filter content or headers for input filtering
3. Optionally wrap the response object with a custom implementation to filter content or headers for output filtering
4. a) Either invoke the next entity in the chain using the FilterChain object (`chain.doFilter()`),
4. b) or not pass on the request/response pair to the next entity in the filter chain to block the request processing
5. Directly set headers on the response after invocation of the next entity in the filter chain.

Specified by:
  `doFilter` in interface `Filter`
Parameters:
  `servletRequest` - The request to process
  `servletResponse` - The response associated with the request
  `filterChain` - Provides access to the next filter in the chain for this filter to pass the request and response to for further processing
Throws:
  `java.io.IOException` - if an I/O error occurs during this filter's processing of the request
  `ServletException` - if the processing fails for any other reason

#### init

    public void init​(FilterConfig filterConfig)
              throws ServletException

Description copied from interface: `javax.servlet.Filter`
Called by the web container to indicate to a filter that it is being placed into service. The servlet container calls the init method exactly once after instantiating the filter. The init method must complete successfully before the filter is asked to do any filtering work.

The web container cannot place the filter into service if the init method either:

- Throws a ServletException
- Does not return within a time period defined by the web container

Specified by:
  `init` in interface `Filter`
Parameters:
  `filterConfig` - The configuration information associated with the filter instance being initialised
Throws:
  `ServletException` - if the initialisation fails

#### handleSimpleCORS

    protected void handleSimpleCORS​(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
                             throws java.io.IOException,
                                    ServletException

Handles a CORS request of type `CorsFilter.CORSRequestType`.SIMPLE.

Parameters:
  `request` - The `HttpServletRequest` object.
  `response` - The `HttpServletResponse` object.
  `filterChain` - The `FilterChain` object.
Throws:
  `java.io.IOException` - an IO error occurred
  `ServletException` - Servlet error propagation
See Also:
  Simple Cross-Origin Request, Actual Request, and Redirects

#### handlePreflightCORS

    protected void handlePreflightCORS​(HttpServletRequest request,
                                       HttpServletResponse response,
                                       FilterChain filterChain)
                                throws java.io.IOException,
                                       ServletException

Handles CORS pre-flight request.

Parameters:
  `request` - The `HttpServletRequest` object.
  `response` - The `HttpServletResponse` object.
  `filterChain` - The `FilterChain` object.
Throws:
  `java.io.IOException` - an IO error occurred
  `ServletException` - Servlet error propagation

#### destroy

    public void destroy()

Description copied from interface: `javax.servlet.Filter`
Called by the web container to indicate to a filter that it is being taken out of service. This method is only called once all threads within the filter's doFilter method have exited or after a timeout period has passed. After the web container calls this method, it will not call the doFilter method again on this instance of the filter.
This method gives the filter an opportunity to clean up any resources that are being held (for example, memory, file handles, threads) and make sure that any persistent state is synchronized with the filter's current state in memory.

Specified by:
  `destroy` in interface `Filter`

#### decorateCORSProperties

    protected static void decorateCORSProperties​(HttpServletRequest request,
                                                 CorsFilter.CORSRequestType corsRequestType)

Decorates the `HttpServletRequest`, with CORS attributes.

- cors.isCorsRequest: Flag to determine if request is a CORS request. Set to `true` if CORS request; `false` otherwise.
- cors.request.origin: The Origin URL.
- cors.request.type: Type of request. Values: `simple` or `preflight` or `not_cors` or `invalid_cors`
- cors.request.headers: Request headers sent as 'Access-Control-Request-Headers' header, for pre-flight request.

Parameters:
  `request` - The `HttpServletRequest` object.
  `corsRequestType` - The `CorsFilter.CORSRequestType` object.

#### join

    protected static java.lang.String join​(java.util.Collection<java.lang.String> elements,
                                           java.lang.String joinSeparator)

Joins elements of `Set` into a string, where each element is separated by the provided separator.

Parameters:
  `elements` - The `Set` containing elements to join together.
  `joinSeparator` - The character to be used for separating elements.
Returns:
  The joined `String`; `null` if elements `Set` is null.

#### checkRequestType

    protected CorsFilter.CORSRequestType checkRequestType​(HttpServletRequest request)

Determines the request type.

Parameters:
  `request` - The HTTP Servlet request
Returns:
  the CORS type

#### isValidOrigin

    @Deprecated
    protected static boolean isValidOrigin​(java.lang.String origin)

Deprecated.
This will be removed in Tomcat 10 Use `RequestUtil.isValidOrigin(String)`
Checks if a given origin is valid or not. Criteria:

- If an encoded character is present in origin, it's not valid.
- If origin is "null", it's valid.
- Origin should be a valid `URI`

Parameters:
  `origin` - The origin URI
Returns:
  `true` if the origin was valid
See Also:
  RFC952

#### isAnyOriginAllowed

    public boolean isAnyOriginAllowed()

Determines if any origin is allowed to make CORS request.

Returns:
  `true` if it's enabled; false otherwise.

#### getExposedHeaders

    public java.util.Collection<java.lang.String> getExposedHeaders()

Obtain the headers to expose.

Returns:
  the headers that should be exposed by browser.

#### isSupportsCredentials

    public boolean isSupportsCredentials()

Determines is supports credentials is enabled.

Returns:
  `true` if the use of credentials is supported otherwise `false`

#### getPreflightMaxAge

    public long getPreflightMaxAge()

Returns the preflight response cache time in seconds.

Returns:
  Time to cache in seconds.

#### getAllowedOrigins

    public java.util.Collection<java.lang.String> getAllowedOrigins()

Returns the `Set` of allowed origins that are allowed to make requests.

Returns:
  `Set`

#### getAllowedHttpMethods

    public java.util.Collection<java.lang.String> getAllowedHttpMethods()

Returns a `Set` of HTTP methods that are allowed to make requests.

Returns:
  `Set`

#### getAllowedHttpHeaders

    public java.util.Collection<java.lang.String> getAllowedHttpHeaders()

Returns a `Set` of headers support by resource.

Returns:
  `Set`

#### isDecorateRequest

    public boolean isDecorateRequest()

Should CORS specific attributes be added to the request.

Returns:
  `true` if the request should be decorated, otherwise `false`