Class CorsFilter
- All Implemented Interfaces:
Filter,FilterConfig,Serializable
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
trueif a CORS request;falseotherwise. - 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.
doFilter(ServletRequest, ServletResponse, FilterChain) and add appropriate locking so that the
doFilter() method executes with a consistent configuration.- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprotected static enumEnumerates varies types of CORS requests. -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringBy default, following headers are supported: Origin,Accept,X-Requested-With, Content-Type, Access-Control-Request-Method, and Access-Control-Request-Headers.static final StringBy default, following methods are supported: GET, POST, HEAD and OPTIONS.static final StringBy default, no origins are allowed to make requests.static final StringBy default, request is decorated with CORS attributes.static final StringBy default, none of the headers are exposed in response.static final StringBy default, time duration to cache pre-flight response is 30 mins.static final StringBy default, support credentials is disabled.static final StringBoolean value, suggesting if the request is a CORS request or not.static final StringAttribute that contains the origin of the request.static final StringThe prefix to a CORS request attribute.static final StringRequest headers sent as 'Access-Control-Request-Headers' header, for pre-flight request.static final StringType of CORS request, of typeCorsFilter.CORSRequestType.static final StringKey to retrieve allowed headers fromFilterConfig.static final StringKey to retrieve allowed methods fromFilterConfig.static final StringKey to retrieve allowed origins fromFilterConfig.static final StringKey to retrieve exposed headers fromFilterConfig.static final StringKey to retrieve preflight max age fromFilterConfig.static final StringKey to determine if request should be decorated.static final StringKey to retrieve support credentials fromFilterConfig.static final StringThe Access-Control-Request-Headers header indicates which headers will be used in the actual request as part of the preflight request.static final StringThe Access-Control-Request-Method header indicates which method will be used in the actual request as part of the preflight request.static final StringThe Origin header indicates where the cross-origin request or preflight request originates from.static final StringThe Access-Control-Allow-Credentials header indicates whether the response to request can be exposed when the omit credentials flag is unset.static final StringThe 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 final StringThe 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 final StringThe 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 final StringThe Access-Control-Expose-Headers header indicates which headers are safe to expose to the API of a CORS API specificationstatic final StringThe Access-Control-Max-Age header indicates how long the results of a preflight request can be cached in a preflight result cache.static final Collection<String> Collectionof media type values for the Content-Type header that will be treated as 'simple'. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprotected CorsFilter.CORSRequestTypecheckRequestType(HttpServletRequest request) Determines the request type.protected static voiddecorateCORSProperties(HttpServletRequest request, CorsFilter.CORSRequestType corsRequestType) Decorates theHttpServletRequest, with CORS attributes.voiddoFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) ThedoFiltermethod 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.Returns aSetof headers support by resource.Returns aSetof HTTP methods that are allowed to make requests.Returns theSetof allowed origins that are allowed to make requests.Obtain the headers to expose.longReturns the preflight response cache time in seconds.protected voidhandlePreflightCORS(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) Handles CORS pre-flight request.protected voidhandleSimpleCORS(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) Handles a CORS request of typeCorsFilter.CORSRequestType.SIMPLE.voidinit()Convenience method for sub-classes to save them having to callsuper.init(config).booleanDetermines if any origin is allowed to make CORS request.booleanShould CORS specific attributes be added to the request.booleanDetermines is supports credentials is enabled.protected static Stringjoin(Collection<String> elements, String joinSeparator) Joins elements ofSetinto a string, where each element is separated by the provided separator.Methods inherited from class jakarta.servlet.GenericFilter
getFilterConfig, getFilterName, getInitParameter, getInitParameterNames, getServletContext, init
-
Field Details
-
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:
-
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:
-
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:
-
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:
-
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:
-
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:
-
REQUEST_HEADER_ORIGIN
The Origin header indicates where the cross-origin request or preflight request originates from.- See Also:
-
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:
-
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:
-
HTTP_REQUEST_ATTRIBUTE_PREFIX
The prefix to a CORS request attribute.- See Also:
-
HTTP_REQUEST_ATTRIBUTE_ORIGIN
Attribute that contains the origin of the request.- See Also:
-
HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST
Boolean value, suggesting if the request is a CORS request or not.- See Also:
-
HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE
Type of CORS request, of typeCorsFilter.CORSRequestType.- See Also:
-
HTTP_REQUEST_ATTRIBUTE_REQUEST_HEADERS
Request headers sent as 'Access-Control-Request-Headers' header, for pre-flight request.- See Also:
-
SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES
Collectionof 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:
-
DEFAULT_ALLOWED_ORIGINS
By default, no origins are allowed to make requests.- See Also:
-
DEFAULT_ALLOWED_HTTP_METHODS
By default, following methods are supported: GET, POST, HEAD and OPTIONS.- See Also:
-
DEFAULT_PREFLIGHT_MAXAGE
By default, time duration to cache pre-flight response is 30 mins.- See Also:
-
DEFAULT_SUPPORTS_CREDENTIALS
By default, support credentials is disabled.- See Also:
-
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:
-
DEFAULT_EXPOSED_HEADERS
By default, none of the headers are exposed in response.- See Also:
-
DEFAULT_DECORATE_REQUEST
By default, request is decorated with CORS attributes.- See Also:
-
PARAM_CORS_ALLOWED_ORIGINS
Key to retrieve allowed origins fromFilterConfig.- See Also:
-
PARAM_CORS_SUPPORT_CREDENTIALS
Key to retrieve support credentials fromFilterConfig.- See Also:
-
PARAM_CORS_EXPOSED_HEADERS
Key to retrieve exposed headers fromFilterConfig.- See Also:
-
PARAM_CORS_ALLOWED_HEADERS
Key to retrieve allowed headers fromFilterConfig.- See Also:
-
PARAM_CORS_ALLOWED_METHODS
Key to retrieve allowed methods fromFilterConfig.- See Also:
-
PARAM_CORS_PREFLIGHT_MAXAGE
Key to retrieve preflight max age fromFilterConfig.- See Also:
-
PARAM_CORS_REQUEST_DECORATE
Key to determine if request should be decorated.- See Also:
-
-
Constructor Details
-
CorsFilter
public CorsFilter()
-
-
Method Details
-
doFilter
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException Description copied from interface:jakarta.servlet.FilterThedoFiltermethod 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.- Parameters:
servletRequest- The request to processservletResponse- The response associated with the requestfilterChain- Provides access to the next filter in the chain for this filter to pass the request and response to for further processing- Throws:
IOException- if an I/O error occurs during this filter's processing of the requestServletException- if the processing fails for any other reason
-
init
Description copied from class:jakarta.servlet.GenericFilterConvenience method for sub-classes to save them having to callsuper.init(config). This is a NO-OP by default.- Overrides:
initin classGenericFilter- Throws:
ServletException- If an exception occurs that interrupts the Filter's normal operation
-
handleSimpleCORS
protected void handleSimpleCORS(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException Handles a CORS request of typeCorsFilter.CORSRequestType.SIMPLE.- Parameters:
request- TheHttpServletRequestobject.response- TheHttpServletResponseobject.filterChain- TheFilterChainobject.- Throws:
IOException- an IO error occurredServletException- Servlet error propagation- See Also:
-
handlePreflightCORS
protected void handlePreflightCORS(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException Handles CORS pre-flight request.- Parameters:
request- TheHttpServletRequestobject.response- TheHttpServletResponseobject.filterChain- TheFilterChainobject.- Throws:
IOException- an IO error occurredServletException- Servlet error propagation
-
decorateCORSProperties
protected static void decorateCORSProperties(HttpServletRequest request, CorsFilter.CORSRequestType corsRequestType) Decorates theHttpServletRequest, with CORS attributes.- cors.isCorsRequest: Flag to determine if request is a CORS request. Set to
trueif CORS request;falseotherwise. - cors.request.origin: The Origin URL.
- cors.request.type: Type of request. Values:
simpleorpreflightornot_corsorinvalid_cors - cors.request.headers: Request headers sent as 'Access-Control-Request-Headers' header, for pre-flight request.
- Parameters:
request- TheHttpServletRequestobject.corsRequestType- TheCorsFilter.CORSRequestTypeobject.
- cors.isCorsRequest: Flag to determine if request is a CORS request. Set to
-
join
Joins elements ofSetinto a string, where each element is separated by the provided separator. -
checkRequestType
Determines the request type.- Parameters:
request- The HTTP Servlet request- Returns:
- the CORS type
-
isAnyOriginAllowed
public boolean isAnyOriginAllowed()Determines if any origin is allowed to make CORS request.- Returns:
trueif it's enabled; false otherwise.
-
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:
trueif the use of credentials is supported otherwisefalse
-
getPreflightMaxAge
public long getPreflightMaxAge()Returns the preflight response cache time in seconds.- Returns:
- Time to cache in seconds.
-
getAllowedOrigins
Returns theSetof allowed origins that are allowed to make requests.- Returns:
Set
-
getAllowedHttpMethods
Returns aSetof HTTP methods that are allowed to make requests.- Returns:
Set
-
getAllowedHttpHeaders
Returns aSetof headers support by resource.- Returns:
Set
-
isDecorateRequest
public boolean isDecorateRequest()Should CORS specific attributes be added to the request.- Returns:
trueif the request should be decorated, otherwisefalse
-