Unable to access libs/granite/csrf/token.json from an external application which is not in AEM
We have a scenario where we need to provide our AEM application header and footer to an external application (this is not in AEM). As we know with AEM 6.1 we need to include <cq:includeClientLib categories="granite.csrf.standalone"/> in order to make all the Form submissions or POST requests working. In our header we have a search bar which is embeded in a form tag. When we enter text and click on search icon it submits the form as a POST request. This works absolutely fine within AEM application. This particular scenario is not working when the AEM application header is consumed by an external application. Its throwing an error saying csrf.js?_=1468868152688:228 XMLHttpRequest cannot load AEMApplicationdomain/libs/granite/csrf/token.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
What I understood from the above error is since it is an external Application which is not in AEM, it might be throwing the CORS(Cross origin request) error. To further analyze I have gone through the following code in /etc/clientlibs/granite/jquery/granite/csrf/source/csrf.js file:
var FIELD_NAME = ':cq_csrf_token',
HEADER_NAME = 'CSRF-Token',
TOKEN_SERVLET = '/libs/granite/csrf/token.json';
var promise, globalToken;
function getToken() {
promise = new Promise();
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
try {
var data = JSON.parse(xhr.responseText);
globalToken = data.token;
promise.resolve(globalToken);
} catch (ex) {
promise.reject(xhr.responseText);
}
}
};
xhr.open('GET', Granite.HTTP.externalize(TOKEN_SERVLET), true);
xhr.send();
}
It is taking the TOKEN_SERVLET path and making an ajax call to a servlet in backend to get the random token ID. Since the TOKEN_SERVLET is a relative url, I have changed it to absolute url by adding AEM application domain to it. In this way when an external application is trying to submit the form which is in AEM, the TOKEN_SERVLET won't end up taking the domain of the external application (HOST) which is not an AEM application. However still I am getting the CORS error saying it cannot access it.
So I assume, though I have changed the TOKEN_SERVLET path to absolute with the domain of AEM application appending to it still its throwing the error since the page is not hosted in the very same AEM application domain but from an external Application domain.
If that is the case how to fix the CORS issue in order to allow external App domains to access /libs/granite/csrf/token.json.