在 CORS / 飞行前响应中省略 access-control-allow-headers

Omitting access-control-allow-headers in CORS / preflight response

我无法找到解释如果对预检请求的响应或对实际 CORS 请求的响应省略时会发生什么的信息 Access-Control-Allow-Headers。我注意到有几个网站说当请求包含 Access-Control-Request-Headers.

时需要 header

我想允许 CORS 使用任何 header 访问我的 API,所以我想知道省略这个 header 是否会做到这一点并允许所有 headers.

我的 API 要求您发送一个包含 OAuth 令牌的 Authorization header,通常客户端还会发送一个 cookie。有些网站说 Access-Control-Allow-Headers 使用 * 仅在 Access-Control-Allow-Credentialsfalse 时用作通配符。

这似乎让我陷入困境,因为我希望 CORS 请求包含凭据(Authorization header 和一个 cookie),但我也想允许所有 header秒。我怎样才能完成这项工作?

第二个问题是为什么我要将请求限制在一组允许的 header 范围内?在我的例子中,API 是一个 GET,它不会在服务器上进行任何更改。我希望允许的来源始终能够检索此信息。在什么情况下,他们包含的 headers 会发挥作用?

I’m having trouble finding information explaining what happens if the response to a preflight request or the response to the actual CORS request omits Access-Control-Allow-Headers. I have noticed that several sites say this header is required when the request includes Access-Control-Request-Headers.

这些站点是正确的:如果预检请求包含 Access-Control-Request-Headers header,那么对该请求的响应必须至少包含 Access-Control-Allow-Headers header,否则 CORS 预检将失败。 CORS 预检成功所需的实际 header 值将根据预检请求中指定的 header 名称而有所不同。

I would like to allow CORS access to my API with any headers, so I’m wondering if omitting this header will do just that and allow all headers.

否,在对预检请求的响应中省略 Access-Control-Allow-Headers header 不算通过。

My API requires that you send an Authorization header containing an OAuth token and typically the client will also send a cookie. There are sites that say that using * for Access-Control-Allow-Headers only acts as a wildcard when Access-Control-Allow-Credentials is false.

接近,但不精确。相反,如果使用 Access-Control-Allow-Credentials: true,则不能对 Access-Control-Allow-Headers 使用通配符。参见 https://fetch.spec.whatwg.org/#http-new-header-syntax

This seems to put me in a bind since I want the CORS request to include credentials (the Authorization header and a cookie) but I also want to allow all headers. How can I make this work?

在这种情况下,您不能使用通配符。您只有一种方法:获取预检请求的 Access-Control-Request-Headers header 中列出的所有 header 名称,并将它们反映在响应的 Access-Control-Allow-Headers header.[=35 中=]

A secondary question is why would I want to restrict the request to an allowed set of headers? In my case the API is a GET which makes no changes on the server. I want allowed origins to always be able to retrieve this information. Under what circumstances would the headers they include play into that?

我可能遗漏了一些东西,但如果允许的来源集是有限的,我认为这不会有问题。但是,如果您允许任意来源,您可能不应该在经过身份验证的端点上允许任意 headers。特别是,允许​​ Authorization 用于任意来源打开通往 client-side 的大门,分发 brute-force 不记名令牌(或 Authorization 通常包含的任何内容);更多关于 https://github.com/whatwg/fetch/issues/251#issuecomment-209265586