Article
· Sep 27, 2016 5m read

Enabling Cross-origin Resource Sharing (CORS) for RESTful Services

Cross-origin Resource Sharing (CORS) is one of the basic security features built into browsers. CORS controls accessing resources from a HTML page in domains other than the original domain. It is particularly important for AJAX calls. Since RESTful services can be used as data provider to any AJAX call, you have to be able to control cross-origin access. By default services are not allowed to do CORS. You are going to learn how to enable it for Ensemble RESTful services.

The Resource Map class (the subclass of %CSP.REST) controls whether CORS is enabled. There are two approaches to do. One way is to define per entry in the UrlMap XData block and another is to set the static class parameter HandleCorsRequest. Although the first approach seems more flexible by providing smaller granularity in the definition, it requires changes in the project source when you enable/disable CORS. This requires deeveloper access to the resource map class. Since CORS is a service security setting, it is subject of deployment rather than development. Therefore the recommended practice is to develop two resource map files (one with CORS disabled and another with enabled) and control by swapping the classes in the Web Application settings. One of the two class can be a subclass of the other, meaning that the only difference between the two classes is the value of the static class parameter. This guide took the second approach.

Before you read

Please read the “Create RESTful Service using Ensemble” guide and deploy the project on an Ensemble server.

Optionally install a HTTP server in your environment listening on a different host and/ or port than your standard Ensemble CSP port. An internal server of any other Caché/ Ensemble instance is sufficient.

Building project using Ensemble Studio

The following section explains how to create the project when you are using Ensemble Studio.

Create a new Studio project (optional)

To organize the components we need to have a Studio Project. To create a new project launch the Ensemble Studio.

Use the File menu and call the New Project menu point. Right after this call the Save Project As menu point.

Create new Resource Map

Resource map is responsible to translate the resource name included by the URL to Ensemble configuration item name. The Resource Map is an Ensemble class created as a subclass of %CSP.REST.

The class can be created by the New Class wizard. The wizard starts from the File à New menu.

Make sure, that the General / Caché Class Definition is selected on the first page of the wizard.

Please use any package and class name on your preference.

Complete the wizard by selecting the Subclass of on the class type page. Enter the name of your non-CORS resource map class you already prepared.

Building project using Atelier

The following section explains how to create the project when you are using Atelier.

Create a new Atelier project

To create a new project launch Atelier, and in the File menu call the New à Project menu point. Please remember, that Atelier requires a project to work on.

Please select the server connection you created prior and the namespace you want to work in.

Create new Resource Map

Resource map is responsible to translate the resource name included by the URL to Ensemble configuration item name. The Resource Map is an Ensemble class created as a subclass of %CSP.REST.

The class can be created by the New Class wizard. The wizard starts from the File à New menu. Please use the General/ Empty class template.

Please use any package and class name on your preference.

Add the non-CORS resource map class you already prepared to the list of superclasses.

Deploy project using Ensemble Management Portal

You need to modify the Web Application settings of your service application. Use the Security Administration of the Management Portal to access the settings. Change the Dispatch class setting of a service configuration from the non-CORS resource map class to the one you are completing.

Implementation

The Resource Map class (the subclass of %CSP.REST) controls whether CORS is enabled. There are two approaches to do. We demonstrate how to enable CORS by setting the static class parameter HandleCorsRequest to 1. It is a recommended practice to develop two resource map files (one with CORS disabled and another with enabled). One of the two class can be a subclass of the other, meaning that the only difference between the two classes is the value of the static class parameter.

Class h2.enablecors.ResourceMap Extends h2.createrestfulservice.ResourceMap
{

Parameter HandleCorsRequest = 1;

}

Create a test page

Place a static HTML page into the HTTP server’s folder structure or into a workstation local folder including an AJAX call to the RESTful service you created. Here is an example.

<html>
<head>
<title> Ensemble RESTful Service </title>
<script src='jquery-2.0.3.min.js'>
</script>
</head>
<body>
<h1>Ensemble RESTful service test page</h1>
<h2>Testing Cross-Origin Resource Sharing</h2>
<div>
<input type='text' placeholder='Enter a valid URL' id='url'/>
<input type='button' value='send data' onclick="(function () {
        var url = document.querySelector('#url');
        $.ajax({
               url: url.value,
               crossDomain: true,
               cache: false,
               contentType: 'application/json',
               method: 'GET',
               success: function(response) {
                       var textfield = document.querySelector('textarea');
                       textfield.value = response
               },
               error: function(xhr,status,error) {
                       alert('Is Cors enabled on your service?\r\nCheck your browser console for message.');
               }
        });
})()"/>
</div>
<textarea style='width:90%;height:20ex;'>
</textarea>
</body>
</html>
​

Please note! I use jQuery convenience library for the AJAX call implementation.

The page invokes a RESTful service and displays the returned response in a textarea field. It works flawless on services with the same origin as the page but throws error when the service is outside the domain.

Running tests

Use the HTML page we created. When CORS is disabled and you try to access a RESTful service not in your domain, you’ll get an error. On error you’ll see a JavaScript alert window popping up.

Look at the browser console as well to read the complete error message.

Enable CORS by changing the Dispatch class name for your service Web Application and the page returns the response in the text area – as expected.

Stay tuned, I’ll be back soon with further reading on Ensemble RESTful web services. The next will be “Consuming RESTful Web Services”.

Discussion (0)0
Log in or sign up to continue