AJAX请求不会发送来自同一域的Cookie集

时间:2014-12-10 17:27:45

标签: javascript ajax cookies xss same-origin-policy

我正在开发一种用户跟踪系统,其工作原理如下:

1)网站管理员在其网站中添加了一个js脚本:

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

2)当用户加载页面时,javascript请求会发送回cookie:

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

(它基本上是一个持续1年的简单cookie)

3)tracking.js对同一个example.com域发出POST XMLHttpRequest,传递一些参数:

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

4)example.com的后端应该读取先前设置的“trackid”cookie,但相反,我没有得到任何cookie请求...通过Chrome检查员分析POST请求,我注意到没有cookie是在请求标头中传递(而对于tracking.js的第一个GET请求通过Set-Cookie正确设置了cookie)。

为什么?起初我认为它可能是与同源政策有关的问题;所以我在后端Web服务器上启用了CORS头。没有结果。所以,我尝试在example.com的相同域名下的网站上加载tracking.js(比如web.example.com)。无论如何,再没有结果......

我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

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(); 
  }

第7行显示XMLHttpRequest上的标志,必须设置该标志才能使用Cookies进行调用,即withCredentials布尔值。默认情况下,调用不使用Cookie。由于这是一个简单的GET请求,因此不会预检,但浏览器将拒绝任何没有Access-Control-Allow-Credentials:true标头的响应,并且不会使响应可用于调用Web内容。