How to Enable Cross Origin Resource Sharing(CORS) support in AEM(Adobe Experience Manager)
Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served.
Sometimes we may have scenarios to expose the AEM services to be invoked from cross origins, this post explains the different approaches to enable the Cross Origin Resource Sharing Supports.
The CORS support is introduced OOB in AEM 6.3 version, refer https://helpx.adobe.com/experience-manager/kt/platform-repository/using/cors-security-article-understand.html for more details.
Enabling CORS for older AEM versions(<6.3)
The request is failed with below exception in browser console while trying to invoke cross origin(service hosted in different domains) services through Ajax.
"Failed to load http://localhost:4503/bin/sampleJSONPService: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access".
There are two approaches to enable the Cross Origin Requests
- JSONP
- CORS Headers
JSONP
JSONP stands for JSON with Padding, JSONP is a method for sending JSON data without worrying about cross-domain issues.
JSONP supports only the GET request method, JSONP works on legacy browsers.
Enable the service to rerun the JSON response with Padding
@SuppressWarnings("serial")
@SlingServlet(
selectors = "json",
paths = "/bin/sampleJSONPService",
methods = "GET")
public class SimpleServlet extends SlingSafeMethodsServlet {
@Override
protected void doGet(final SlingHttpServletRequest req,
final SlingHttpServletResponse resp) throws ServletException, IOException {
resp.setHeader("Content-Type", "application/json");
resp.setHeader("X-Content-Type-Options", "");
String callback=req.getParameter("callback");
JSONObject response = new JSONObject();
try {
response.put("test1", "testvalue1");
response.put("test2", "testvalue2");
response.put("test3", "testvalue3");
response.put("test4", "testvalue4");
} catch (JSONException e) {
e.printStackTrace();
}
if(callback!=null && !callback.trim().equals("")) {
resp.getWriter().write( callback + "("+response.toString()+ ")");
}else
{
resp.getWriter().write(response.toString());
}
}
}
The above service return the JSON response with padding
Invoke the JSONP service from Ajax
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous">
</script>
</head>
<body>
Test Data (<span class="testData">Default</span>)
<script>
var dataUrl = 'http://localhost:4503/bin/sampleJSONPService.json?callback=?';
$.ajax({
url: dataUrl,
dataType: 'jsonp',
success: function(data) {
jQuery('.testData').html('').text(data.test1)
}});
</script>
</body>
</html>
This will provide the response without any issue
test({"test1":"testvalue1","test2":"testvalue2","test3":"testvalue3","test4":"testvalue4"})
CORS Headers
Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. CORS also supports other types(other than GET) of HTTP requests, CORS is supported by most modern web browsers.
The Access-Control-Allow-Origin response header indicates whether the response can be shared with resources with the given origin.
e.g.
Access-Control-Allow-Origin "*" supports the Cross Origin requests from all domains
Access-Control-Allow-Origin "https://example.com" supports Cross Origin requests only from https://example.com
Enabling Access-Control-Allow-Origin header
The header can be enabled directly in the service response or thorough apache configuration
Though Service response - Add Access-Control-Allow-Origin header with required value in the service response
@SuppressWarnings("serial")
@SlingServlet(
selectors = "json",
paths = "/bin/sampleJSONPService",
methods = "GET")
public class SimpleServlet extends SlingSafeMethodsServlet {
@Override
protected void doGet(final SlingHttpServletRequest req,
final SlingHttpServletResponse resp) throws ServletException, IOException {