Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell tomcat to support CORS for static content? [duplicate]

This question: Servers that supports CORS? was about regular servlets; and I do know how to set headers to control CORS.

My question is how do I configure Tomcat to serve static content under CORS restrictions.

like image 235
Vlad Patryshev Avatar asked Aug 21 '12 04:08

Vlad Patryshev


2 Answers

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

References:

  • Tomcat 7
  • Tomcat 9

Pretty much the only thing you have to do is edit the global web.xml in CATALINA_HOME/conf and add the 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 ====================== -->

Be aware, though, that Firefox does not like Access-Control-Allow-Origin: * and requests with credentials (cookies): when responding to a credentialed request, server must specify a domain, and cannot use wild carding.

If you want to debugs requests in this situation, please be aware that CORS headers are only sent if there is a cross-origin request according to this flow-chart: CORS flow chart

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

like image 183
Johannes Jander Avatar answered Nov 11 '22 22:11

Johannes Jander


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

like image 20
monsur Avatar answered Nov 11 '22 23:11

monsur