Search code examples
javaapachetomcatcorsactivation

Enable CORS Apache Tomcat 7.0.52


I have been trying to enable CORS on my Microsoft Azure Apache Tomcat server and I have tried quite a lot of techniques but I am still unable to get CORS up and running. I have added this to the web.xml file and no luck in getting that enabled.

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
  <init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value>*</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.methods</param-name>
    <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.headers</param-name>
    <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
  </init-param>
  <init-param>
    <param-name>cors.exposed.headers</param-name>
    <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
  </init-param>
  <init-param>
    <param-name>cors.support.credentials</param-name>
    <param-value>true</param-value>
  </init-param>
  <init-param>
    <param-name>cors.preflight.maxage</param-name>
    <param-value>10</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

I keep getting an error:

XMLHttpRequest cannot load url&output=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://url.net' is therefore not allowed access.

Any suggestions on how I can achieve this quickly? I have been looking at loads of resources online and I can't get it to work unfortunately. Looking forward to your suggestions.


Solution

  • Your web.xml looks ok, so I'm expecting it does set the response header as requested (your question doesn't make this clear either way).

    However on some modern browsers (Chrome, Firefox etc.), you'll find they won't allow wildcard origins:

    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>*</param-value>
    </init-param>
    

    Instead, you'll need to specify an expected domain, for greater security:

    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>http://otherdomain.com</param-value>
    </init-param>
    

    Usefully, the list of origins can be comma separated:

    A * can be specified to enable access to resource from any origin. Otherwise, a whitelist of comma separated origins can be provided. Eg: http://www.w3.org, https://www.apache.org. Defaults: * (Any origin is allowed to access the resource)

    Source: https://tomcat.apache.org/tomcat-7.0-doc/config/filter.html