Cross-Domain Cookies
Yes, it is absolutely possible to get the cookie from domain1.com by domain2.com. I had the same problem for a social plugin of my social network, and after a day of research I found the solution.
First, on the server side you need to have the following headers:
header("Access-Control-Allow-Origin: http://origin.domain:port");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST");
header("Access-Control-Allow-Headers: Content-Type, *");
Within the PHP-file you can use $_COOKIE[name]
Second, on the client side:
Within your ajax request you need to include 2 parameters
crossDomain: true
xhrFields: { withCredentials: true }
Example:
type: "get",
url: link,
crossDomain: true,
dataType: 'json',
xhrFields: {
withCredentials: true
}
As other people say, you cannot share cookies, but you could do something like this:
- centralize all cookies in a single domain, let's say cookiemaker.com
- when the user makes a request to example.com you redirect him to cookiemaker.com
- cookiemaker.com redirects him back to example.com with the information you need
Of course, it's not completely secure, and you have to create some kind of internal protocol between your apps to do that.
Lastly, it would be very annoying for the user if you do something like that in every request, but not if it's just the first.
But I think there is no other way...
As far as I know, cookies are limited by the "same origin" policy. However, with CORS you can receive and use the "Server B" cookies to establish a persistent session from "Server A" on "Server B".
Although, this requires some headers on "Server B":
Access-Control-Allow-Origin: http://server-a.domain.com
Access-Control-Allow-Credentials: true
And you will need to send the flag "withCredentials" on all the "Server A" requests (ex: xhr.withCredentials = true;
)
You can read about it here:
http://www.html5rocks.com/en/tutorials/cors/
https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS