How to tell tomcat about CORS support for static content?

This question: Servers supporting CORS? relate to regular servlets; and I know how to set headers for CORS control.

My question is how to configure Tomcat to serve static content according to CORS restrictions.

+7
source share
3 answers

Here is the Tomcat filter for adding CORS support: https://bitbucket.org/jsumners/corsfilter

+1
source

Starting with Tomcat 7.0.41, you can easily control CORS behavior through the built-in filter.

References:

Almost the only thing you need to do is edit the global web.xml in CATALINA_HOME/conf and add a filter definition:

  <! - =================== Built In Filter Definitions ====================== ->

       ...

      <filter>
        <filter-name> CorsFilter </filter-name>
        <filter-class> org.apache.catalina.filters.CorsFilter </filter-class>
      </filter>
      <filter-mapping>
        <filter-name> CorsFilter </filter-name>
        <url-pattern> / * </url-pattern>
      </filter-mapping>

     <! - ===================== Built In Filter Mappings ====================== ->

However, keep in mind that Firefox does not like Access-Control-Allow-Origin: * and asks for credentials (cookies): when responding to a request with credentials, the server must specify a domain and cannot use wildcards.

If you want to debug requests in this situation, keep in mind that CORS headers are sent only if, according to this flowchart, there is a cross-source request: CORS flow chart

(Tomcat.apache.org/tomcat-8.0-doc/images/cors-flowchart.png)

+15
source

Hello, Vlad! This is a very late answer, now you must understand all this. If someone comes across the same question, this is the answer.

Obviously, you know about the CORS filter and that Tomcat filters will only apply to servlets.

For all static content to flow through some servlet, Tomcat has a special DefaultServet - this is what you are looking for.

Basically, we just need to include it in the deployment descriptor file (for example, WEB-INF / web.xml), for example, for example:

 <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <servlet> <servlet-name>default</servlet-name> <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> 

Thus, Tomcat filters, in our case, the CORS filter will be enabled for static content.

To verify that the CORS filter actually sets headers, such as Access-Control-Allow-Origin , we will need to add another header, such as an Origin request. For example:

 curl -H 'Origin: http://localhost/test' -i http://myserver/crossOrigin.resource 

This way you will see something like:

 HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Access-Control-Allow-Origin: http://localhost/test Access-Control-Allow-Credentials: true Accept-Ranges: bytes ... 
+1
source

All Articles