I can’t seem to get cookies set on my browser in javascript to be sent as part of a jQuery ajax request to a sub-domain web application.
I have two web applications, one on a root domain and one on a sub-domain. To get around cross site scripting restrictions, my sub-domain web application implements a global action filter to add the Access-Control-Allow-Origin header to the root domain of all its http responses. This allows ajax calls from the root domain to the sub-domain to work.
But, when I create a cookie in javascript using the following code…
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = 'searchId=' + ids.generateGUID() + ';domain=' + ".root.example.com" + ';path=/;expires=' + myDate;
… the cookie is not passed in the subsequent ajax requests to the-sub domain server.
I thought that the CORS header and setting the domain and path in the cookie would allow the sub domain web application access to the cookie but the browsers (chrome 21.0.1180.89 & firefox 17.0.1) don’t seem to supply the cookie.
Am I misunderstanding browser cookie access restrictions when using sub-domains and ajax requests?
Thanks
In order for cookies to work with CORS, you need to do two things.
First, your server needs to respond with the following header:
Second, your XmlHttpRequest object needs to set the
withCredentialsproperty:This should send the remote domain cookies in the request, although the cookie must be set by the remote server.
Your JS code itself still will not have access to the cookies, nor can it set cookies on a remote domain. There is no way, AFIAK for JS code to access another domain’s cookies.