Tuesday 18 August 2015

Enable CORS in Alfresco and how to use cross-origin requests

CORS stands for Cross-Origin Resource Sharing. This means by enabling CORS in alfresco, we can make requests from one repository to the other. Requests can be either GET or POST or any other. This is also called cross-domain requests or cross-domain ajax calls.

List of browser and their versions that support CORS.

  1. Chrome - 4.0+
  2. Firefox - 3.5+
  3. Opera mini - 12.0+
  4. Safari - 4.0+
  5. IE - 10+

CORS Enabling:

CORS enabling is just two steps process which must be done.
  1. Add the following jars to WEB-INF/lib folder in alfresco.
    cors-filter and java-property-utils
    The latest jars can be found at Click here or you can simply download it from HERE

    If you want to enable CORS in share, place both jars at same location in share.

    Or if you want to enable CORS for all web applications, then a better way is to place both jars to tomcat/lib folder. By doing this, we won't have to then place jars inside every web-apps lib.

    Make sure to remove all other jars with same name but different version if any, otherwise, it will create conflict.
  2. Modify web.xml file placed at WEB-INF/web.xml in alfresco/share.
    Add below snippet of code.

    <filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
    </filter>

    <filter-mapping>
    <filter-name>CORS</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>

    'filter' can be placed anywhere in web.xml but 'filter mapping' must be placed before authentication filters.
That is all. This will enable all cross-domain requests.

How do we use?

JQuery supports cross domain ajax calls. Therefore, add the jquery dependency in javascript dependencies in the ftl file.

Below is a sample jQuery ajax GET request. Setting the parameter "crossDomain" to true will make cross requests.

jQuery.ajax({
url: http://your_domain:your_port + "/alfresco/service/api/login?u=admin&pw=admin",
type : "GET",
crossDomain : true,
async : false,
success : function(res) {},
error : function() {},
});

Thank!!