Class CORSFilter

  • All Implemented Interfaces:
    javax.servlet.Filter

    public final class CORSFilter
    extends java.lang.Object
    implements javax.servlet.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 helps to determine nature of request downstream.

    • 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.

    See Also:
    CORS specification
    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
      static class  CORSFilter.CORSRequestType
      Enumerates varies types of CORS requests.
    • Constructor Summary

      Constructors 
      Constructor Description
      CORSFilter()  
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      CORSFilter.CORSRequestType checkRequestType​(javax.servlet.http.HttpServletRequest request)
      Determines the request type.
      static void decorateCORSProperties​(javax.servlet.http.HttpServletRequest request, CORSFilter.CORSRequestType corsRequestType)
      Decorates the HttpServletRequest, with CORS attributes.
      void destroy()  
      void doFilter​(javax.servlet.ServletRequest servletRequest, javax.servlet.ServletResponse servletResponse, javax.servlet.FilterChain filterChain)  
      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()
      Returns a Set of headers that should be exposed by browser.
      long getPreflightMaxAge()
      Returns the preflight response cache time in seconds.
      void handleInvalidCORS​(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, javax.servlet.FilterChain filterChain)
      Handles a CORS request that violates specification.
      void handleNonCORS​(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, javax.servlet.FilterChain filterChain)
      Handles a request, that's not a CORS request, but is a valid request i.e.
      void handlePreflightCORS​(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, javax.servlet.FilterChain filterChain)
      Handles CORS pre-flight request.
      void handleSimpleCORS​(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, javax.servlet.FilterChain filterChain)
      Handles a CORS request of type CORSFilter.CORSRequestType.SIMPLE.
      void init​(javax.servlet.FilterConfig filterConfig)  
      boolean isAnyOriginAllowed()
      Determines if any origin is allowed to make CORS request.
      boolean isLoggingEnabled()
      Determines if logging is enabled or not.
      private boolean isOriginAllowed​(java.lang.String origin)
      Checks if the Origin is allowed to make a CORS request.
      boolean isSupportsCredentials()
      Determines is supports credentials is enabled
      static boolean isValidOrigin​(java.lang.String origin)
      Checks if a given origin is valid or not.
      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.
      private void log​(java.lang.String message)  
      private void parseAndStore​(java.lang.String allowedOrigins, java.lang.String allowedHttpMethods, java.lang.String allowedHttpHeaders, java.lang.String exposedHeaders, java.lang.String supportsCredentials, java.lang.String preflightMaxAge, java.lang.String loggingEnabled, java.lang.String decorateRequest)
      Parses each param-value and populates configuration variables.
      private java.util.Set<java.lang.String> parseStringToSet​(java.lang.String data)
      Takes a comma separated list and returns a Set.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • filterConfig

        private javax.servlet.FilterConfig filterConfig
        Holds filter configuration.
      • allowedOrigins

        private final java.util.Collection<java.lang.String> allowedOrigins
        A Collection of origins consisting of zero or more origins that are allowed access to the resource.
      • anyOriginAllowed

        private boolean anyOriginAllowed
        Determines if any origin is allowed to make request.
      • allowedHttpMethods

        private final java.util.Collection<java.lang.String> allowedHttpMethods
        A Collection of methods consisting of zero or more methods that are supported by the resource.
      • allowedHttpHeaders

        private final java.util.Collection<java.lang.String> allowedHttpHeaders
        A Collection of headers consisting of zero or more header field names that are supported by the resource.
      • exposedHeaders

        private final java.util.Collection<java.lang.String> exposedHeaders
        A Collection of exposed headers consisting of zero or more header field names of headers other than the simple response headers that the resource might use and can be exposed.
      • supportsCredentials

        private boolean supportsCredentials
        A supports credentials flag that indicates whether the resource supports user credentials in the request. It is true when the resource does and false otherwise.
      • preflightMaxAge

        private long preflightMaxAge
        Indicates (in seconds) how long the results of a pre-flight request can be cached in a pre-flight result cache.
      • loggingEnabled

        private boolean loggingEnabled
        Controls access log logging.
      • decorateRequest

        private boolean decorateRequest
        Determines if the request should be decorated or not.
      • 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_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_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
      • HTTP_METHODS

        public static final java.util.Collection<java.lang.String> HTTP_METHODS
        Collection of HTTP methods. Case sensitive.
      • COMPLEX_HTTP_METHODS

        public static final java.util.Collection<java.lang.String> COMPLEX_HTTP_METHODS
        Collection of non-simple HTTP methods. Case sensitive.
      • SIMPLE_HTTP_METHODS

        public static final java.util.Collection<java.lang.String> SIMPLE_HTTP_METHODS
        Collection of Simple HTTP methods. Case sensitive.
      • SIMPLE_HTTP_REQUEST_HEADERS

        public static final java.util.Collection<java.lang.String> SIMPLE_HTTP_REQUEST_HEADERS
        Collection of Simple HTTP request headers. Case in-sensitive.
      • SIMPLE_HTTP_RESPONSE_HEADERS

        public static final java.util.Collection<java.lang.String> SIMPLE_HTTP_RESPONSE_HEADERS
        Collection of Simple HTTP request headers. Case in-sensitive.
      • SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES

        public static final java.util.Collection<java.lang.String> SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES
        Collection of Simple HTTP request headers. Case in-sensitive.
      • DEFAULT_ALLOWED_ORIGINS

        public static final java.lang.String DEFAULT_ALLOWED_ORIGINS
        By default, all 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 turned on.
        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_LOGGING_ENABLED

        public static final java.lang.String DEFAULT_LOGGING_ENABLED
        By default, access log logging is turned off
        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_LOGGING_ENABLED

        public static final java.lang.String PARAM_CORS_LOGGING_ENABLED
        Key to retrieve access log logging flag.
        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​(javax.servlet.ServletRequest servletRequest,
                             javax.servlet.ServletResponse servletResponse,
                             javax.servlet.FilterChain filterChain)
                      throws java.io.IOException,
                             javax.servlet.ServletException
        Specified by:
        doFilter in interface javax.servlet.Filter
        Throws:
        java.io.IOException
        javax.servlet.ServletException
      • init

        public void init​(javax.servlet.FilterConfig filterConfig)
                  throws javax.servlet.ServletException
        Specified by:
        init in interface javax.servlet.Filter
        Throws:
        javax.servlet.ServletException
      • handleSimpleCORS

        public void handleSimpleCORS​(javax.servlet.http.HttpServletRequest request,
                                     javax.servlet.http.HttpServletResponse response,
                                     javax.servlet.FilterChain filterChain)
                              throws java.io.IOException,
                                     javax.servlet.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
        javax.servlet.ServletException
        See Also:
        Simple Cross-Origin Request, Actual Request, and Redirects
      • handlePreflightCORS

        public void handlePreflightCORS​(javax.servlet.http.HttpServletRequest request,
                                        javax.servlet.http.HttpServletResponse response,
                                        javax.servlet.FilterChain filterChain)
                                 throws java.io.IOException,
                                        javax.servlet.ServletException
        Handles CORS pre-flight request.
        Parameters:
        request - The HttpServletRequest object.
        response - The HttpServletResponse object.
        filterChain - The FilterChain object.
        Throws:
        java.io.IOException
        javax.servlet.ServletException
      • handleNonCORS

        public void handleNonCORS​(javax.servlet.http.HttpServletRequest request,
                                  javax.servlet.http.HttpServletResponse response,
                                  javax.servlet.FilterChain filterChain)
                           throws java.io.IOException,
                                  javax.servlet.ServletException
        Handles a request, that's not a CORS request, but is a valid request i.e. it is not a cross-origin request. This implementation, just forwards the request down the filter chain.
        Parameters:
        request - The HttpServletRequest object.
        response - The HttpServletResponse object.
        filterChain - The FilterChain object.
        Throws:
        java.io.IOException
        javax.servlet.ServletException
      • handleInvalidCORS

        public void handleInvalidCORS​(javax.servlet.http.HttpServletRequest request,
                                      javax.servlet.http.HttpServletResponse response,
                                      javax.servlet.FilterChain filterChain)
        Handles a CORS request that violates specification.
        Parameters:
        request - The HttpServletRequest object.
        response - The HttpServletResponse object.
        filterChain - The FilterChain object.
        Throws:
        java.io.IOException
        javax.servlet.ServletException
      • destroy

        public void destroy()
        Specified by:
        destroy in interface javax.servlet.Filter
      • decorateCORSProperties

        public static void decorateCORSProperties​(javax.servlet.http.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

        public 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

        public CORSFilter.CORSRequestType checkRequestType​(javax.servlet.http.HttpServletRequest request)
        Determines the request type.
        Parameters:
        request -
        Returns:
      • isOriginAllowed

        private boolean isOriginAllowed​(java.lang.String origin)
        Checks if the Origin is allowed to make a CORS request.
        Parameters:
        origin - The Origin.
        Returns:
        true if origin is allowed; false otherwise.
      • log

        private void log​(java.lang.String message)
      • parseAndStore

        private void parseAndStore​(java.lang.String allowedOrigins,
                                   java.lang.String allowedHttpMethods,
                                   java.lang.String allowedHttpHeaders,
                                   java.lang.String exposedHeaders,
                                   java.lang.String supportsCredentials,
                                   java.lang.String preflightMaxAge,
                                   java.lang.String loggingEnabled,
                                   java.lang.String decorateRequest)
                            throws javax.servlet.ServletException
        Parses each param-value and populates configuration variables. If a param is provided, it overrides the default.
        Parameters:
        allowedOrigins - A String of comma separated origins.
        allowedHttpMethods - A String of comma separated HTTP methods.
        allowedHttpHeaders - A String of comma separated HTTP headers.
        exposedHeaders - A String of comma separated headers that needs to be exposed.
        supportsCredentials - "true" if support credentials needs to be enabled.
        preflightMaxAge - The amount of seconds the user agent is allowed to cache the result of the pre-flight request.
        loggingEnabled - Flag to control logging to access log.
        Throws:
        javax.servlet.ServletException
      • parseStringToSet

        private java.util.Set<java.lang.String> parseStringToSet​(java.lang.String data)
        Takes a comma separated list and returns a Set.
        Parameters:
        data - A comma separated list of strings.
        Returns:
        Set
      • isValidOrigin

        public static boolean isValidOrigin​(java.lang.String origin)
        Checks if a given origin is valid or not. Criteria:
        • If an encoded character is present in origin, it's not valid.
        • Origin should be a valid URI
        Parameters:
        origin -
        Returns:
        See Also:
        RFC952
      • isLoggingEnabled

        public boolean isLoggingEnabled()
        Determines if logging is enabled or not.
        Returns:
        true if it's enabled; false otherwise.
      • 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()
        Returns a Set of headers that should be exposed by browser.
        Returns:
      • isSupportsCredentials

        public boolean isSupportsCredentials()
        Determines is supports credentials is enabled
        Returns:
      • 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