9

I am new to Cross-origin resource sharing and I want to enable it in a Tomcat 5.5 server. Anybody can give me some hint how can this be achieved?

I want to set the header universally for all requests, and to allow all origins (Access-Control-Allow-Origin: *)

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Pablo
  • 2,834
  • 5
  • 25
  • 45
  • http://stackoverflow.com/questions/1653308/access-control-allow-origin-multiple-origin-domains – austin Mar 08 '12 at 08:24
  • Sorry, but that does not answer to my question. It's fine for me to allow all domains (by using `*`), but what I need is to configure it for Tomcat. – Pablo Mar 08 '12 at 08:44
  • Hi, I think the accepted answer is outdated, please consider switching to my answer below so that people have the chance to see there exists a standard mechanism in Tomcat now. – Johannes Jander Apr 08 '15 at 13:36

2 Answers2

23

If it's a static site, then starting with Tomcat 7.0.41, you can easily control CORS behavior via a built-in filter.

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.

Johannes Jander
  • 4,974
  • 2
  • 31
  • 46
  • 1
    +1, I think this was a perfect answer to the question. – DarkHorse Feb 07 '14 at 07:09
  • any way to have multiple domains without wildcard? firefox rejects commas in this header – FlavorScape Feb 24 '15 at 23:41
  • I tried to follow this answer, but I had no clue where in the xml hierarchy I should add this definition. Can somebody please add this clue to the answer, for the people that are not so falimiar with the particular xml hierarchy in web.xml? thanks! – Alkis Mavridis Sep 06 '18 at 11:12
3

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

monsur
  • 45,581
  • 16
  • 101
  • 95