6

RFC 6265 states that a user-agent should proceed in the following way when receiving a Set-Cookie header:

If the Domain attribute is set:

  • Set the cookie's domain to the domain-attribute.
  • Set the cookie's host-only-flag to false.

If the Domain attribute is not set:

  • Set the cookie's domain to the canonicalized request-host.
  • Set the cookie's host-only-flag to true.

This is all clear. The confusion comes with this paragraph:

If the user agent receives a new cookie with the same cookie-name, domain-value, and path-value as a cookie that it has already stored, the existing cookie is evicted and replaced with the new cookie.

Let's take an example, with two cookies received on the domain www.example.com:

Set-cookie: name=value
Set-Cookie: name=value; Domain=www.example.com

The domain (and path) will be the same for both cookies, but the first one will have the host-only-flag set to true, and the second one to false.

Reading the RFC, it looks like it doesn't matter when comparing the two cookies, and they should be considered equivalent anyway, but I'm not sure my interpretation is correct.

Should the user-agent replace the first cookie with the second one, or should it store both of them?

4

1 回答 1

5

让您感到困惑的段落是关于为 cookie分配新值的能力(以及更改/刷新 cookie 到期日期)。如果不是这样写,HTTP 客户端将需要存储多个具有相同名称的 cookie,并且需要决定在下一次请求时发送到 HTTP 服务器的另一个标准。

关于你问题的第二部分:

host-only-flag = false如果在同一个请求中指定了这两个 cookie,则第二个“获胜”,因此将存储一个带有 的 cookie 。

如果这两个 cookie 来自不同的请求,则第二个会覆盖第一个,因为它们在 cookie 名称(指定)、域值(一旦指定,一旦派生)和路径值(派生)中匹配。存储它们时,浏览器 cookie 数据库中的条目仅在 host-only-flag 上有所不同。

当客户端向服务器发出新请求时,此主机专用标志生效(来自 RFC6265 的片段):

The user agent MUST use an algorithm equivalent to the following
algorithm to compute the "cookie-string" from a cookie store and a
request-uri:

1.  Let cookie-list be the set of cookies from the cookie store that
    meets all of the following requirements:

    *  Either:

           The cookie's host-only-flag is true and the canonicalized
           request-host is identical to the cookie's domain.

        Or:

           The cookie's host-only-flag is false and the canonicalized
           request-host domain-matches the cookie's domain.

细节在于如何比较域。匹配算法在第 5.1.3 节中指定。

本质上,如果域是用前导“。”指定的,那么您可以让 cookie 对所有子域都有效。

但是,当域被省略时(因此服务器从请求中暗示),情况永远不会发生,因为域中总是需要相同的匹配。

进一步研究确定:

实际上,浏览器存储已在 cookie 中指定的域,并在前面添加.(因为www.example.com它将存储.www.example.com),以便请求subdomain.www.example.com也将返回该 cookie。当没有指定域时,.将存储没有前置的普通域,因此对子域的请求将不包括该 cookie。

于 2013-05-07T10:45:53.760 回答