通过 HTTPS 的 HTTP Cookie 和 Ajax 请求 [英] HTTP Cookies and Ajax requests over HTTPS

查看:36
本文介绍了通过 HTTPS 的 HTTP Cookie 和 Ajax 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道之前已经以各种形式询问过这个问题,但我似乎无法解决这个问题.我尝试使用 jQuery 和原生 JS API 来发出 Ajax 请求.

I know this has been asked before in various forms, but I can't seem to get around the problem. I have tried using both jQuery and the native JS API to make the Ajax requests.

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

My situation is the following (see attached diagram):

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

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

Before anybody starts a lecture on cross-domain requests let me state a couple of things:

  • 我知道这是一个跨域请求(不同的协议),这就是服务器在响应中设置 Access-Control-Allow-Origin 标头的原因(我正在使用 Chrome 和Firefox,两者都支持 CORS)
  • 不过,我还知道 HTTP cookie 应该可以通过 HTTPS 进行管理(请参阅 此处),因为主机是相同的
  • (编辑)为一般域(例如 .domain.ext)正确设置了 cookie,并且既没有设置 HttpOnly 也没有设置安全标志
  • I know that this is a cross-domain request (different protocol), and that's why the Server sets the Access-Control-Allow-Origin header in the response (and I am using Chrome and Firefox, both of which support CORS)
  • What I also know, though, is that the HTTP cookie ought to be manageable over HTTPS (see here) since the host is the same
  • (EDIT) The cookie is properly set for the general domain (e.g. .domain.ext) and neither the HttpOnly nor the Secure flags are set

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

So, why, why, why doesn't the browser pass on the cookie when making the HTTPS Ajax call? Any ideas? I am about to lose my mind...

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

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

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

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

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

推荐答案

好的,cookie问题找到了.

Ok, found the solution to the cookie problem.

请参阅XHR 规范jQuery 文档StackOverflow.

在切换协议和/或子域时发送 cookie 的解决方案是将 withCredentials 属性设置为 true.

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

例如(使用jQuery)

E.g. (using jQuery)

 $.ajax( {
   /* Setup the call */
   xhrFields: {
     withCredentials: true
   }
 });

这篇关于通过 HTTPS 的 HTTP Cookie 和 Ajax 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆