Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping the cookie after a cross-domain ajax request

A javascript application running on 10.0.0.1 tries to authenticate it's users with cross-domain ajax calls.

The request looks like:

function test(again){
  $.ajax({
    type: 'GET',
    url: 'http://example.com/userinfo',
    dataType: 'json',
    success: function(userinfo){
      if(again)
        test(false);}});}
test(true);

The first response from the server tries to set a cookie:

Access-control-allow-origin:http://10.0.0.1
Set-Cookie:PHPSESSID=uuj599r4k1ohp48f1poobil665; expires=Sat, 28-Jan-2012 17:10:40 GMT; path=/

But the second request does not include this cookie, nor do any other ajax requests to that domain.

I am not trying to read the cookie for another domain, I just want the application on the other domain to be able to set and read its own cookie.

Is this possible?

I have tested in Chrome and Firefox 9.

like image 995
Etienne Laurin Avatar asked Jan 13 '12 17:01

Etienne Laurin


People also ask

Do cookies get sent with AJAX requests?

Basically, ajax request as well as synchronous request sends your document cookies automatically.

Do cookies persist across domains?

As we know that cookie set by one domain cannot be accessed by the another domain. But cookie set to main domain can be accessed by subdomains. Example: Cookie set to domain “maindomain.com” can be accessed by any sub domain of main domain, that is subdomain.maindomain.com, anysub.maindomain.com.

Why is the browser not setting cookies after an AJAX request returns?

Browsers will ignore the set-cookie response header if the cookie exceeds the browsers limit, and it will not set the cookie.

Can cross-domain access cookies?

Chrome will keep supporting them for 2020, and 2021. This means that it will no longer be possible to track visitors across domains on the websites that do not support the mentioned cookies. So, only Chrome browser visitors will be trackable across domains utilizing the feature mentioned in this article.


2 Answers

server should set header:

response.Headers.Add("Access-Control-Allow-Credentials", "true");

client set to:

xhrFields: {
  withCredentials: true
}
like image 69
Teddy Avatar answered Oct 31 '22 01:10

Teddy


As long as you are using a browser which supports CORS, cookies on the AJAX request should work. But you must set withCredentials on the XMLHttpRequest to true.

See: The withCredentials attribute

I don't use JQuery but here's a question that deals specifically with setting withCredentials via JQuery.

Sending credentials with cross-domain posts?

like image 27
Debby Mendez Avatar answered Oct 31 '22 01:10

Debby Mendez