java 使用相同的 cookie 名称调用 HttpServletResponse.addCookie() 是否安全?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3193163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is calling HttpServletResponse.addCookie() with the same cookie name safe?
提问by tbk
Is calling
正在呼叫
HttpServletResponse.addCookie();
(from servlet-api-2.5) multiple times using a cookie with the same name safe?
(来自 servlet-api-2.5)多次使用同名的 cookie 安全吗?
Safe in the sense of that there is a deterministic behavior, e.g. the subsequent calls will be ignored (the first wins) or the subsequent calls will always replace the cookie or something like that?
在存在确定性行为的意义上是安全的,例如,后续调用将被忽略(第一个获胜)或后续调用将始终替换 cookie 或类似的东西?
Example:
例子:
HttpServletResponse response = ...;
response.addCookie(new Cookie("foo", "bar"));
response.addCookie(new Cookie("foo", "42"));
Which value will be transferred to and stored by the browser?
浏览器将传输和存储哪个值?
采纳答案by JoseK
Updated answer - as the comments from @skaffman and @Stephen C show this is not ideal practice.
更新的答案 - 正如@skaffman 和 @Stephen C 的评论表明这不是理想的做法。
The RFC Spec at http://www.ietf.org/rfc/rfc2109.txtstates
http://www.ietf.org/rfc/rfc2109.txt 上的 RFC 规范指出
The NAME=VALUE attribute-value pair must come first in each cookie. If an attribute appears more than once in a cookie, the behavior is undefined.
NAME=VALUE 属性-值对必须出现在每个 cookie 中。 如果一个属性在 cookie 中出现多次,则行为未定义。
On Tomcat server, the behaviour is the actual headers sent to the browser:
在 Tomcat 服务器上,行为是发送到浏览器的实际标头:
Set-Cookie: foo=bar
Set-Cookie: foo=42
设置曲奇:foo=bar
设置曲奇:foo=42
Here foo gets overwritten. Reading the cookie later gives you 42.
这里 foo 被覆盖。稍后阅读 cookie 会给你 42。
回答by johnkaplantech
Additional comment - note that setting different sub-domains on cookies with the same name in the same response changes the behavior. I just tested saving cookies with the same name but different sub-domains on latest versions of java 1.6/firefox/safari/chrome on my mac, and it behaved as expected, saving both cookies. I understand this behavior is not guaranteed by the spec, but just sayin' it may be helpful to be aware of it.
附加注释 - 请注意,在同一响应中为具有相同名称的 cookie 设置不同的子域会改变行为。我刚刚在我的 mac 上测试了在最新版本的 java 1.6/firefox/safari/chrome 上保存具有相同名称但不同子域的 cookie,它的行为符合预期,同时保存了两个 cookie。我知道规范不保证这种行为,但只是说意识到它可能会有所帮助。

