Thursday, July 23, 2015

Cors Filter in Tomcat

CORS stands for Cross Origin Resource Sharing. This is a way to handle Cross domain requests. CORS as a concept is supported by W3C consortium. It is enabled on server side by putting Access-Control-* headers.

The origin header is put by clients side browsers and by enabling CORS we can ask the server to honour the request.

Tomcat supports CORS filter which can be enabled by hooking the filter in web.xml. A minimalist configuration is


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

CORS filter implements the javax.Servlet.Filter interface and hence provides a transparent way of enabling CORS capability in applications.

One things to note is that by default CORS filter only supports GET, POST and HEAD. If you want to enable more protocol like PUT and DELETE, than you will have to register it as follows:

 <init-param>
    <param-name>cors.allowed.methods</param-name>
    <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
  </init-param>

Put the above as a child of <filter> tag. 

For a complete description of the other details of CORS filter refer to the Tomcat documentation at https://tomcat.apache.org/tomcat-7.0-doc/config/filter.html

No comments:

Post a Comment