10

I am not able to set cookie when domain filed is added using cross site request. I am trying to achieve that by calling request through jquery ajax.

Is it possible to get it working in other browsers than firefox?

Some request Headers:

Accept:application/json, text/javascript, */*; q=0.01
Content-Length:55
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:localhost:53862
Origin:http://localhost:54265
Referer:http://localhost:54265/

Response Headers:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:x-requested-with, origin, content-type, accept, Proxy-Connection
Access-Control-Allow-Methods:GET,POST,PUT,OPTIONS, DELETE
Access-Control-Allow-Origin:http://localhost:54265
Set-Cookie:Auth=l_hash=123456&user=xyzl&remember_me=false; expires=Fri, 18 Jan 2013 13:42:10 GMT; domain=localhost; path=/

Code:

$.ajax({
    type: "PUT",
    url: apiHost + "api/account/login/",
    data: $("#loginBarForm").serialize(),
    dataType: "json",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
    crossDomain: true,

    xhrFields: {
        withCredentials: true
    },
});

Everything is fine in firefox. Chrome is not setting cookie. Only if domain field is removed all is working on every browser. I can see that in next request (after setting cookie) that cookie appears in header. Example from firefox request after response setting cookie (when response had domain field):

Cookie: Auth=l_hash=123456&user=xyz&remember_me=false
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Mariusz
  • 3,054
  • 2
  • 20
  • 31
  • Are you sure `localhost` is a valid domain for `Set-Cookie` header? According to [RFC](http://www.ietf.org/rfc/rfc2109.txt), it must contain at least one "embedded" dot. FireFox may implement this in a less restrictive way. Try your IP-address instead. – Stan Dec 19 '12 at 20:09
  • @Stan Thank you so much, please post it as an answer. – Mariusz Dec 20 '12 at 07:22

2 Answers2

8

I had this same problem, and it turned out that the browser settings were blocking third-party cookies (Chrome > Settings > Advanced Settings > Privacy > Content Settings > Block third-party cookies and site data). Allowing the cookies resolved the problem!

Andrew M. Andrews III
  • 1,989
  • 18
  • 23
  • Yes, this solved my problem after hours of frustration! Only in my case, I had Firefox blocking third-party cookies, and Chrome allowing them. – alexw Feb 18 '16 at 15:46
  • Also Google will start phasing out third-party cookies from Q1 2024 : https://www.techcircle.in/2023/05/19/google-will-start-phasing-out-third-party-cookies-from-q1-2024 – Seyed Ali Mahmoody May 20 '23 at 08:28
7

I think the problem can be with localhost, which is not a valid domain for Set-Cookie header. According to RFC, it must contain at least one "embedded" dot. FireFox may implement this in a less restrictive way. Try your IP-address instead.

Stan
  • 8,683
  • 9
  • 58
  • 102