Carmine Giangregorio
Carmine Giangregorio

Reputation: 973

AJAX request doesn't send Cookies set from same domain

I'm developing a sort of user-tracking system, that works as follows:

1) A webmaster adds a js script in his website:

<script src="http://example.com/in/tracking.js"></script>

2) When a user loads the page, the javascript request send back a cookie in response:

Set-Cookie:trackid=c1d7fde9cf87a9501cea57cedde97998;Version=1;Comment=;Domain=example.com;Path=/;Max-Age=31556926

(it's basically a simple cookie that lasts for 1 year)

3) The tracking.js makes a POST XMLHttpRequest, to the same example.com domain, passing some parameters:

theAjaxRequest.open("POST","http://example.com/in",true);
theAjaxRequest.setRequestHeader("Content-type", "multipart/form-data");
theAjaxRequest.send(parameters);

4) The backend of example.com should then read the previously set "trackid" cookie, but, instead, I get no cookies on request... By analyzing the POST request via Chrome inspector, I noted that no cookies are passed in request headers (while the first GET request for tracking.js sets correctly the cookie via Set-Cookie).

How come? At first I assumed it may be a problem related to same-origin-policy; so I enabled CORS headers on back-end web server. No results. So, I tried to load tracking.js on a website under same domain of example.com (say web.example.com). Anyway, no results again...

Am I missing something?

Upvotes: 0

Views: 1991

Answers (1)

GIgio2k
GIgio2k

Reputation: 36

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

var invocation = new XMLHttpRequest();
var url = 'http://bar.other/resources/credentialed-content/';

function callOtherDomain(){
  if(invocation) {
    invocation.open('GET', url, true);
    invocation.withCredentials = true;
    invocation.onreadystatechange = handler;
    invocation.send(); 
  }

Line 7 shows the flag on XMLHttpRequest that has to be set in order to make the invocation with Cookies, namely the withCredentials boolean value. By default, the invocation is made without Cookies. Since this is a simple GET request, it is not preflighted, but the browser will reject any response that does not have the Access-Control-Allow-Credentials: true header, and not make the response available to the invoking web content.

Upvotes: 1

Related Questions