Configuring CORS filter on the default Jetty Server on Fuse-6.1

Solution Unverified - Updated -

Environment

  • Red Hat JBoss Fuse
    • 6.1.x

Issue

  • We would like to know how you would configure the CORS filters on Fuse default Jetty server. There are certain REST services on Fuse that we want to be accessed over ajax on a web application.
  • The @CrossOriginResourceSharing annotation on our REST interfaces work if we shift our services to an embedded jetty configuration. However we want the REST services to run on the default jetty but when we do that the @CrossOriginResourceSharing annotation is not picked up and the ajax call fails saying (Reason: CORS header 'Access-Control-Allow-Origin' missing).
  • The jetty documentation says that CORS configuration is done over web.xml. How does that relate to the default jetty on Fuse as we don't see any web.xml open for configuration. The only configuration we see is in /etc/jetty.xml.

Resolution

  • There is an enableCORS parameter that is available in camel-rest-dsl, http://camel.apache.org/rest-dsl.html, starting camel version 2.15. Hence, this is available in Fuse 6.2.1.

  • For the earlier versions, you will manually have to add CORS headers to the response. You can do this with the following code below,

**
 * @author Viral Gohel
 *
 */
@Provider
public class CORSFilter implements ContainerResponseFilter {

    /*
     * (non-Javadoc)
     *
     * @see javax.ws.rs.container.ContainerResponseFilter#filter(javax.ws.rs.
     * container.ContainerRequestContext,
     * javax.ws.rs.container.ContainerResponseContext)
     */
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
            throws IOException {
        responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
        responseContext.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
        responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        responseContext.getHeaders().add("Access-Control-Max-Age", "1209600");
    }
}

  • You can then register the above class in <jaxrs:providers> or if using camel-cxf transport, in <camelcxf:providers>.
  • There is also a quickstart, /jboss-fuse-6.1.0.redhat-379/quickstarts/secure-soap, which has a class, EnableCORSInterceptor.java.

This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.

Comments