Tomcat 7 and disabling CORSGeek Inc.
Tomcat 7 is a fantastic Java Servlet container and I’ve used it to serve a number of web applications. In addition to serving out web browser content, it can be used to handle an API backend.
I ran into a challenge with serving Bonita BPM and the BonitaSoft REST API is the Cross-Origin-Resource-Sharing (CORS) default implementation. Put simply, it was too restrictive for my application. I was using an AngularJS frontend to access resources in Bonita BPM (users, processes, etc…) and I was consistently getting this error in Chrome:
XMLHttpRequest cannot load http://localhost:8080/bonita/API/user/1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9888' is therefore not allowed access.
I’ve run into this problem before, and I figured that I could use a JSONP request (this will bypass the CORS restriction). For one application, that worked very well. Specifically, I could make a login request and parse the response for success or failure. However, in order to continue to use the full API, I needed to get around the security restrictions.
The simplest way to disable the CORS restrictions on Tomcat 7 is to make an edit to the web.xml file in the CATALINA_HOME/conf directory. Add (or edit) this code just before the closing tag:
<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>
Once this has been done, restart Tomcat and make the API request. No more Access-Control-Allow-Origin error.