Javascript 提取不发送 Cookie header (CORS)

标签 javascript cookies attributes fetch

我正在尝试在 javascript 提取 CORS 请求中将 Cookie 发送到 PHP 脚本。请求从 https://sub1.example.com 开始,包含以下选项:

let response = await fetch('https://sub2.example.com/target.php', {
    method: "POST",
    headers: headers,
    body: formData,
    mode: 'cors',
    credentials: 'include',
    cache: 'no-store'
});

相应的 PHP Script 设置了以下 Headers:

header('Access-Control-Allow-Origin: https://www.example.com');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With, Set-Cookie, Cookie, Bearer');

但是 Cookie header 没有随请求一起发送。我也试过:

let headers = new Headers();
headers.set('Cookie', document.cookie);

那也没有效果。我到底做错了什么?

我检查了开发工具中的网络选项卡。 PHP 脚本中的 $_COOKIE 也是空的。绝对没有错误。我还可以看到 Cookie header 是在任何非 CORS fetch 请求中发送的。

编辑:这是其中一个 Cookie 的设置:

Name: PHPSESSID
Path: /
Secure: true
SameSite: none

我无法共享域,因为它不是公开的。但是 Cookie 域与请求 header 中的来源具有相同的值(减去 https://)。

编辑 2:更改了获取 URL 以使发生的事情更清楚。

最佳答案

问题

请注意,取决于

  • cookie 的 Path 属性的值,
  • cookie 的 Domain 属性的有效值,
  • cookie 的Secure 属性的值,
  • cookie 的有效值 SameSite attribute ,
  • 请求的发出和目标来源,

cookie 可能附加也可能不附加到请求中。与您的案例特别相关的是 Domain 属性;查看MDN's page on the topic :

The Domain attribute specifies which hosts can receive a cookie. If unspecified, the attribute defaults to the same host that set the cookie, excluding subdomains. If Domain is specified, then subdomains are always included. Therefore, specifying Domain is less restrictive than omitting it. However, it can be helpful when subdomains need to share information about a user.

您在源 https://sub1.example.com 上按如下方式设置 cookie:

Set-Cookie: PHPSESSID=whatever; Path=/; SameSite=None; Secure

因此,该 cookie 将附加到目标来源为 https://sub1.example.com 而不是其他来源的(已认证)请求。

解决方案

如果您希望将您的 cookie 发送到域为 example.com 子域的所有安全来源,您需要将其 Domain 显式设置为 example .com.


关于使用 fetch 发送 cookies

Fetch standard指定 forbidden header names 的列表; Cookie 就是其中之一。您不能在使用 fetch 发送的请求上设置名为 Cookie 的 header ;标准简单forbids it .如果要将现有 cookie 附加到跨源请求,请使用 'include' value for the credentials parameter传入 fetch 选项。

关于Javascript 提取不发送 Cookie header (CORS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70590447/

相关文章:

javascript - 如何使用 JavaScript 在我们的网站上获取 Facebook 最近的帖子?

c++ - QNetworkCookieJar 中的 setCookiesFromUrl() 和 cookiesForUrl

javascript - React 中的 props 不应该被更改/突变的原因是因为 React 希望元素尽可能可预测吗?

validation - 如何检查验证属性是否仅有空格

javascript - 在 Z 时间内从大小为 N 的数组中获取 Z 个随机项?

javascript - 如何扩展对象数组中的子数组并删除字符串某些元素

javascript - 输入验证 JavaScript?

asp.net-mvc - ASP.NET MVC-信用卡数据的安全临时存储

php - Symfony 4 Remember Me 不起作用,浏览器重启时 cookie 被破坏

c++ - 在 GCC 中为类使用属性打包