本文介绍了Access-Control-Allow-Credentials 的意义何在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

发送 cookie 的默认值是 SameSite=Lax,这意味着 cookie 是为 GET 请求发送的,但在 POST 时被阻止.

The default value for sending cookies is SameSite=Lax, which means cookies are sent for GET requests, but blocked for POST.

对于跨源 GET 请求,响应会因 Same-Origin-Policy 而被阻止,除非响应包含 Access-Control-Allow-Origin.

With a cross origin GET request, the response is blocked anwyay due to the Same-Origin-Policy, unless the response contains Access-Control-Allow-Origin.

为什么 Access-Control-Allow-Origin 还不够?

您为什么要返回 Access-Control-Allow-Origin: someDomain.com 而不返回 Access-Control-Allow-Credentials?

Why would you ever want to return Access-Control-Allow-Origin: someDomain.com without also returning Access-Control-Allow-Credentials?

为什么允许来自受信任域的跨源 GET 请求,但仅在发送 cookie 时才阻止响应?

Why allow a cross origin GET request from a trusted domain, but block the response only if the cookie was sent?

推荐答案

在存在 cookie 的情况下,允许跨源共享的风险要大得多,因为这可能会将用户的私人信息泄露给恶意脚本.如果没有 cookie,该脚本只能访问公共信息 - 只需从任何计算机导航到 URL 即可访问相同的信息.

Allowing cross-origin sharing is much riskier in the presence of cookies, since that's what can reveal a user's private information to a malicious script. Without cookies, the script can only access public information—the same information that could be accessed by just navigating to the URL from any computer.

因此,Access-Control-Allow-Credentials 的存在标志着一个重要的安全转折点,并有效区分了公共信息和私人信息的共享.

So the existence of the Access-Control-Allow-Credentials marks an important security inflection point, and usefully distinguishes between sharing public and private information.

例如,假设您有一个用于分发股票行情数据的 API,并且您希望允许来自其他站点的脚本访问此 API.CORS 是必要的,因为同源策略将阻止这些脚本查看数据.不过,不需要 cookie.所以该站点可以简单地使用 * 作为 Access-Control-Allow-Origin 并完成.没有共享任何私人数据的风险.

For example, let's say you have an API that's distributing stock ticker data and you want to allow scripts from other sites to access this API. CORS is necessary since the Same Origin Policy will otherwise prevent those scripts from seeing the data. There's no need for cookies, though. So the site can simply use * for Access-Control-Allow-Origin and be done. There's no risk of sharing any private data.

相比之下,想要启用用户特定数据共享的站点必须通过将 Access-Control-Allow-Credentials 设置为 true 来选择加入.此外,站点被迫指定允许的特定站点,因为在这种情况下 *Access-Control-Allow-Origin 无效.

By contrast, a site that wants to enable the sharing of user-specific data will have to opt-in by setting Access-Control-Allow-Credentials to true. Moreover, the site is forced to specify the specific sites allowed, since * is not valid for Access-Control-Allow-Origin in this case.

这篇关于Access-Control-Allow-Credentials 的意义何在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 05:37
查看更多