使用 XMLHttpRequest 进行 302 重定向后的 Cookie 管理

Cookie management after 302 redirection with XMLHttpRequest

本文关键字:Cookie 管理 重定向 XMLHttpRequest 进行 使用      更新时间:2023-09-26

我正在为 ownCloud 开发一个 Firefox OS 客户端。当我尝试登录并将用户凭据发送到服务器时,我需要获取我将在每个请求中用于在ownCloud中进行身份验证的cookie作为响应。

我的问题是,正如我在 Wireshark 中看到的那样,cookie 是通过 HTTP 302 消息发送的,但我无法在我的代码中读取此消息,因为 Firefox 会自动处理它,并且我读取了最终的 HTTP 200 消息,其中没有 cookie 信息

request.reponseText; 
request.getAllResponseHeaders();

所以我的问题是,是否有任何方法可以读取此HTTP 302消息标头,或者我是否可以在发送下一个请求之前从Firefox OS获取cookie,甚至使Firefox OS自动添加cookie。我使用以下代码进行开机自检:

request = new XMLHttpRequest({mozSystem: true});
request.open('post', serverInput, true);
request.withCredentials=true;
request.addEventListener('error', onRequestError);
request.setRequestHeader("Cookie",cookie_value);
request.setRequestHeader("Connection","keep-alive");  
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send(send_string);
if(request.status == 200 || request.status==302){
  response = request.responseText;
  var headers = request.getAllResponseHeaders();
  document.getElementById('results').innerHTML="Server found";
  loginSuccessfull();
}else{
  alert("Response not found");
  document.getElementById('results').innerHTML="Server NOT found";
}

"mozAnon

布尔值:将此标志设置为 true 将导致浏览器在获取资源时不公开源和用户凭据。最重要的是,这意味着除非使用 setRequestHead 明确添加,否则不会发送 cookie。

莫兹系统

布尔值:将此标志设置为 true 允许建立跨站点连接,而无需服务器使用 CORS 选择加入。需要设置 mozAnon:true,即这不能与发送 cookie 或其他用户凭据结合使用。[0]

我不确定您是否是owncloud开发人员,但是如果您是并且可以访问服务器,则应尝试设置CORS标头。[1] 也许您可以建立代理服务器并让您的应用程序连接到启用了 CORS 的代理服务器?

还有一个 withCredentials 属性 [2],您可以在 xhr 对象的实例上设置。 看起来它会添加标头Access-Control-Request-Headers: "cookies"并发送 HTTP 选项请求,这是预检 [3]。 因此,这仍然需要服务器端对 CORS 的支持。[4]

虽然根据内部评论 [5],这似乎不应该工作,但我能够从模拟器运行它并查看请求和响应标头:

var x = new XMLHttpRequest({ mozSystem: true });
x.open('get', 'http://stackoverflow.com');
x.onload = function () { console.log(x.getResponseHeader('Set-Cookie')); };
x.setRequestHeader('Cookie', 'hello=world;');
x.send();

如果响应标头存在,您可能希望在 onload 事件中重新分配 document.cookie,而不是记录它(并非每个站点在每个请求上都设置 cookie)。 您还需要将请求标头设置为 document.cookie 本身。

[0] https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#XMLHttpRequest%28%29

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

[2] https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#Properties

[3] https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests

[4] http://www.html5rocks.com/en/tutorials/cors/#toc-making-a-cors-request

[5] https://bugzilla.mozilla.org/show_bug.cgi?id=966216#c2