Search code examples
ajaxhttpcookiescross-domainsame-origin-policy

What can cause a cookie not to be set on the client?


I have a web application that uses jQuery.ajax to perform a request to another host (right now actually the same because I'm using different ports of "localhost"). The server then returns a cookie.

The cookie value in the HTTP response as shown in Chrome's Dev Tools is

Set-Cookie: MyUserSession=JxQoyzYm1VfESmuh-v22wyiyLREyOkuQWauziTrimjKo=;expires=Sun, 10 Feb 2013 22:08:47 GMT;path=/api/rest/

and so has an expiry of 4 hours in the future.

However, the cookie does not get stored and sent with subsequent requests (tested in both Chrome and Firefox). I first thought it must be "10-Feb-2013" instead of "10 Feb 2013" but that doesn't make a difference. Chrome also shows "Expires" as "Invalid date" on the cookies tab of the response, but that might as well be a Dev Tools bug.

Any ideas?


Solution

  • I think I found the solution. Since during development, my server is at "localhost:30002" and my web app at "localhost:8003", they are considered different hosts regarding CORS. Therefore, all my requests to the server are covered by CORS security rules, especially Requests with credentials. "Credentials" include cookies as noted on that link, so the returned cookie was not accepted because I did not pass

    xhrFields: {
      withCredentials: true
    }
    

    to jQuery's $.ajax function. I also have to pass that option to subsequent CORS requests in order to send the cookie.

    I added the header Access-Control-Allow-Credentials: true on the server side and changed the Access-Control-Allow-Origin header from wildcard to http://localhost:8003 (port number is significant!). That solution now works for me and the cookie gets stored.