使用浏览器的 session cookie 获取 CORS 身份验证

CORS fetch authentication using Browser's session cookie

我有一个存储 session cookie 的服务器,您可以使用在浏览器中运行的页面 (foo.com/login.html) 登录它。然后,浏览器会为该域存储一个 session cookie。

现在我想要另一个页面 (bar.com) 在初始化时使用 JavaScript 向第一页 (foo.com/authenticate) 发出 GET 请求,该页面应该检查 session cookie 存在于浏览器中并验证它,如果正确,他应该用 session 的用户名响应(但是这是从 cookie 中检索的)。当然,如果 foo.com.

存在 session cookie,我当然无法签入 bar.com 的 JavaScript

为了解决这个问题,我 运行 遇到了一些问题,其中之一当然是 CORS。我设法通过在 foo.com 前面放置一个反向代理来避免这个问题,该代理将所有必需的 CORS headers 添加到响应中。除了添加 headers,代理只通过隧道请求(例如 rev-proxy.com/authenticate -> foo.com/authenticate)

现在,当我直接从另一个浏览器 window(例如 rev-proxy.com/authenticate)通过 rev 代​​理调用处理程序时,我得到了正确的响应。来自 foo.com 后端的处理程序找到 session cookie,读出用户名并将其传回。但是当我尝试从 bar.com 内部的 JavaScript 进行相同的调用时(fetch("rev-proxy.com/authenticate")),我收到 null,这意味着他没有找到 cookie(注意请求本身有状态 200,意味着它确实到达了 foo.com) 的后端。

我觉得我遗漏了浏览器如何使用 cookie 的关键点,但我找不到任何关于我的特定问题的有用信息,因为我认为这是一个相当不寻常的问题。

the MDN documentation:

fetch won’t send cookies, unless you set the credentials init option. (Since Aug 25, 2017. The spec changed the default credentials policy to same-origin. Firefox changed since 61.0b13.)