简体   繁体   English

调用具有相同cookie名称的HttpServletResponse.addCookie()是否安全?

[英]Is calling HttpServletResponse.addCookie() with the same cookie name safe?

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, eg 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? 哪个值将被传输到浏览器并存储?

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.txt states RFC规范http://www.ietf.org/rfc/rfc2109.txt说明

The NAME=VALUE attribute-value pair must come first in each cookie. NAME = VALUE属性值对必须在每个cookie中排在第一位。 If an attribute appears more than once in a cookie, the behavior is undefined. 如果属性在cookie中出现多次,则行为未定义。

On Tomcat server, the behaviour is the actual headers sent to the browser: 在Tomcat服务器上,行为是发送到浏览器的实际标头:

Set-Cookie: foo=bar Set-Cookie:foo = bar
Set-Cookie: foo=42 Set-Cookie:foo = 42

Here foo gets overwritten. 这里foo被覆盖了。 Reading the cookie later gives you 42. 稍后阅读cookie会给你42。

Additional comment - note that setting different sub-domains on cookies with the same name in the same response changes the behavior. 附加注释 - 请注意,在同一响应中使用相同名称的cookie设置不同的子域会更改行为。 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. 我刚刚在我的mac上测试了在最新版本的java 1.6 / firefox / safari / chrome上保存了具有相同名称但不同子域的cookie,并且它按预期运行,节省了两个cookie。 I understand this behavior is not guaranteed by the spec, but just sayin' it may be helpful to be aware of it. 我理解规范不保证这种行为,但只是说'了解它可能会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM