Access-Control-Allow-Origin header 必须包含方案吗?

Must the Access-Control-Allow-Origin header include scheme?

我在 CORS 定义方面遇到了一些问题,我有一个问题(不是关于 CORS 的一般问题 - 我没意见 - 只是关于官方规范和用法):

根据 IETF,如果 Origin header 被传递并且它是 URL,则 URL 必须完全序列化,并且必须包括方案和主机(和可选端口)。来自 https://www.rfc-editor.org/rfc/rfc6454#section-7.1:

The Origin header field has the following syntax:

origin              = "Origin:" OWS origin-list-or-null OWS
origin-list-or-null = %x6E %x75 %x6C %x6C / origin-list
origin-list         = serialized-origin *( SP serialized-origin )
serialized-origin   = scheme "://" host [ ":" port ]
                   ; <scheme>, <host>, <port> from RFC 3986

至少,我认为我理解正确。

IETF 说 Access-Control-Allow-Origin header 的格式必须遵循相同的格式。来自 http://www.w3.org/TR/cors/#access-control-allow-origin-response-header:

Access-Control-Allow-Origin = "Access-Control-Allow-Origin" ":" origin-list-or-null | "*"

以及指向 Origin header 页面的链接。

但是,我已经看到许多示例(在 SO 和其他地方)显示 ACAO headers 没有 方案(即不是确切的 'mirror' 的来源 header),例如他们显示这是在请求中传递的:

Origin: http://www.example.com

这是 'correct' 响应:

Access-Control-Allow-Origin: www.example.com

那么 ACAO header 有效吗?我认为 ACAO header 必须是 Origin header 值(或“*”或 'null')的精确镜像。

如果我用 包含方案的 ACAO header 响应,用户代理是否应该接受它?还是以 UA-by-UA 为基础?如果 Origin 包含端口号怎么办 - 我是否需要将其包含在 ACAO 响应中 header,有或没有方案?

正如您所提到的,RFC 6454 明确定义来源的语法:

origin              = "Origin:" OWS origin-list-or-null OWS
origin-list-or-null = %x6E %x75 %x6C %x6C / origin-list
origin-list         = serialized-origin *( SP serialized-origin )
serialized-origin   = scheme "://" host [ ":" port ]

CORS W3C recommandation明确引用相同的定义。

Access-Control-Allow-Origin = "Access-Control-Allow-Origin" ":" origin-list-or-null | "*"

所以下面的header是无效的

Access-Control-Allow-Origin: www.example.com

不能被用户代理接受

When generating an Origin header field, the user agent MUST meet the following requirements:

Each of the serialized-origin productions in the grammar MUST be the ascii-serialization of an origin.

这一点特别重要,因为 same-origin policy:

The same-origin policy is one of the cornerstones of security for many user agents, including web browsers.

关于端口号问题的第二部分,ASCII serialization of an origin algorithm 指出:

  1. If the port part of the origin triple is different from the default port for the protocol given by the scheme part of the origin triple:

Append a U+003A COLON code point (":") and the given port, in base ten, to result.