47

我知道以前曾以各种形式提出过这个问题,但我似乎无法解决这个问题。我尝试使用 jQuery 和本机 JS API 来发出 Ajax 请求。

我的情况如下(见附图):

  1. 浏览器发出 HTTP 请求
  2. 服务器响应并设置持久 Cookie
  3. 浏览器发出 HTTP Ajax 请求,Cookie 存在就好
  4. 服务器按预期响应,更新 Cookie
  5. 浏览器发出 HTTPS Ajax 请求,Cookie 不再存在(?!)
  6. 服务器给出“默认”响应,因为没有 Cookie(意外行为)

在任何人开始关于跨域请求的讲座之前,让我先声明几件事:

  • 我知道这是一个跨域请求(不同的协议),这就是服务器Access-Control-Allow-Origin在响应中设置标头的原因(我使用的是 Chrome 和 Firefox,两者都支持CORS
  • 不过,我还知道 HTTP cookie 应该可以通过 HTTPS 进行管理(请参阅此处),因为主机是相同的
  • (编辑)为通用域(例如 .domain.ext)正确设置了 cookie,并且既没有设置 HttpOnly 也没有设置 Secure 标志

那么,为什么,为什么,为什么浏览器在进行 HTTPS Ajax 调用时不传递 cookie?有任何想法吗?我快要失去理智了……

     +-----------+ HTTP Request     +-----------+
     |Browser    |+---------------->|Server     |
     +-----------+                  +-----------+

                   HTTP Response
                  <----------------+
                   Set-cookie

                   Ajax HTTP Req.
                  +---------------->
                   Cookie (OK)

                   HTTP Response
                  <----------------+
                   Set-cookie (OK)

                   Ajax HTTPS Req.
                  +---------------->
                   No Cookie (!!!)
4

2 回答 2

78

好的,找到了cookie问题的解决方案。

请参阅XHR 规范jQuery 文档StackOverflow

The solution to have the cookies sent when switching protocol and/or subdomain is to set the withCredentials property to true.

E.g. (using jQuery)

 $.ajax( {
   /* Setup the call */
   xhrFields: {
     withCredentials: true
   }
 });
于 2012-04-20T15:31:44.410 回答
0

Document.cookie and Ajax Request does not share the cookie. Otherwise, ajax can't access the cookies from document.cookie or the response headers. They can only be controlled by the remote domain.

If you first get response including cookie from server by ajax, Since that you can request ajax communication with cookie to server.

For this case, you write such as below code (jQuery)

 $.ajax({
      xhrFields : {
           withCredentials : true
      }
 });

See this article and demo

于 2014-07-02T09:32:27.097 回答