【问题标题】:Cookie management after 302 redirection with XMLHttpRequest使用 XMLHttpRequest 进行 302 重定向后的 Cookie 管理
【发布时间】:2015-03-06 17:16:48
【问题描述】:

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

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

request.reponseText; 
request.getAllResponseHeaders();

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

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";
}

【问题讨论】:

    标签: javascript cookies xmlhttprequest firefox-os http-status-code-302


    【解决方案1】:

    "mozAnon

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

    moz系统

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

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

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

    虽然这似乎不应该基于内部 cmets [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();
    

    如果响应标头存在(并非每个站点都在每个请求上设置 cookie),您可能希望在 onload 事件中重新分配 document.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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-11
      • 2017-02-06
      • 1970-01-01
      • 2018-02-14
      • 2012-03-10
      • 1970-01-01
      • 2015-11-20
      相关资源
      最近更新 更多