Access-Control-Allow-Credentials 详解

Last Modified: 2022/10/29

详解

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

默认情况下,跨域请求不会包含 cookie,这与 JSON-P 等其他跨域技术不同。 JSON-P 总是在请求中包含 cookie,这种行为可能导致一类漏洞,称为跨站点请求伪造或 CSRF。

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

为了减少 CORS 中出现 CSRF 漏洞的机会,CORS 要求服务器和客户端都确认可以在请求中包含 cookie。这样做会使 cookie 成为共识,而不是在没有任何控制的情况下被动发生的事情。

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

客户端代码必须将 XMLHttpRequest 上的 withCredentials 属性设置为 true 才能授予权限。

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

但是,仅仅该 HEADER 是不够的。服务器必须使用 Access-Control-Allow-Credentials 响应头进行响应。将此响应头设置为 true 意味着服务器允许将 cookie(或其他用户凭据)包含在跨域请求中。

当配置了xhr.withCredentials 为 true 时,必须在后端增加 response 头信息 Access-Control-Allow-Origin,且必须指定具体域名,而不能指定为 *。

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

如果希望跨域凭据请求正常工作,我们还需要确保浏览器没有阻止第三方 cookie。

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

请注意,无论您是发出同源请求还是跨源请求,都需要确保站点不受 CSRF 的影响(尤其是当您的请求包含 cookie 时)。

补充说明

Just want to add to this a little to comment on the meaning of "exposed." The spec doesn't require a pre-flight (additional roundtrip to check if the server will allow credentials) for GET requests. Instead of preflighting, the browser will just always make the request, sending cookies if withCredentials is set, but then when it receives the response, if withCredentials was set, it will only deliver/expose the result to the calling javascript if the response has the Access-Control-Allow-Credentials header set. If no header, it doesn't expose the response, effectively black-holing it.

Credentials are cookies, authorization headers, or TLS client certificates.

有问题吗?点此反馈!

温馨提示:反馈需要登录