Enable RESTful Service CORS Support 

Introduction

Goal

Enable CORS support to allow access to Hippo RESTful services via AJAX.

Use Case

Calling a Hippo RESTful service via Ajax confronts you with the same-origin policy. By default, browsers do not allow cross-domain Ajax requests. Hippo supports Cross-Origin Resource Sharing (CORS) to allow such cross-domain requests.

Enabling CORS

To enable CORS in a Hippo RESTful service, first add one extra CXF dependency to the site:

site/pom.xml

<dependency>
  <groupId>org.apache.cxf</groupId>
  <artifactId>cxf-rt-rs-security-cors</artifactId>
  <version>${cxf.version}</version>
</dependency> 

Second, add some Spring configuration to the site:

site/src/main/resources/META-INF/hst-assembly/overrides/cors-support.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

  <import resource="classpath:/org/hippoecm/hst/site/optional/jaxrs/SpringComponentManager-rest-jackson.xml" />

  <bean id="jaxrsRestCorsFilter" class="org.apache.cxf.rs.security.cors.CrossOriginResourceSharingFilter"/>

  <bean id="customJaxrsRestEntityProviders" class="org.springframework.beans.factory.config.ListFactoryBean">
    <property name="sourceList">
      <list>
        <ref bean="jaxrsRestCorsFilter"/>
      </list>
    </property>
  </bean>

</beans> 

Ensure that the resource classpath:/org/hippoecm/hst/site/optional/jaxrs/SpringComponentManager-rest-jackson.xml is only included once in your Spring configuration override files. When other Spring configuration override files also include this resource, they will override the bean customJaxrsRestEntityProviders again and no CORS filter will be added.

That's it. Each call to the RESTful service that includes an 'Origin' HTTP header will now automatically include the following header in the response:

Access-Control-Allow-Origin: *

That will grant all domains access to the RESTful service. More finegrained access control can be achieved by configuring the jaxrsRestCorsFilter Spring bean, or by adding annotations to your REST resource classes. See the CXF CORS documentation for examples.