服务器端删除cookies的正确方法 [英] Correct way to delete cookies server-side
问题描述
对于我的身份验证过程,我会在用户登录时创建一个唯一的令牌并将其放入用于身份验证的 cookie 中.
For my authentication process I create a unique token when a user logs in and put that into a cookie which is used for authentication.
所以我会从服务器发送这样的东西:
So I would send something like this from the server:
Set-Cookie: token=$2a$12$T94df7ArHkpkX7RGYndcq.fKU.oRlkVLOkCBNrMilaSWnTcWtCfJC; path=/;
适用于所有浏览器.然后要删除一个 cookie,我发送了一个类似的 cookie,其中 expires
字段设置为 1970 年 1 月 1 日
Which works on all browsers. Then to delete a cookie I send a similar cookie with the expires
field set for January 1st 1970
Set-Cookie: token=$2a$12$T94df7ArHkpkX7RGYndcq.fKU.oRlkVLOkCBNrMilaSWnTcWtCfJC; path=/; expires=Thu, Jan 01 1970 00:00:00 UTC;
这在 Firefox 上运行良好,但不会删除 IE 或 Safari 上的 cookie.
And that works fine on Firefox but doesn't delete the cookie on IE or Safari.
那么删除 cookie 的最佳方法是什么(最好不使用 JavaScript)?设置过期方法看起来很笨重.还有为什么这在 FF 中有效,而在 IE 或 Safari 中无效?
So what is the best way to delete a cookie (without JavaScript preferably)? The set-the-expires-in-the-past method seems bulky. And also why does this work in FF but not in IE or Safari?
推荐答案
使用 发送相同的 cookie 值;expires
附加不会破坏cookie.
Sending the same cookie value with ; expires
appended will not destroy the cookie.
通过设置一个空值并包括一个 expires
字段来使 cookie 无效:
Invalidate the cookie by setting an empty value and include an expires
field as well:
Set-Cookie: token=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT
请注意,您不能强制所有浏览器删除 cookie.客户端可以以这样的方式配置浏览器,即 cookie 仍然存在,即使它已过期.如上所述设置值可以解决这个问题.
Note that you cannot force all browsers to delete a cookie. The client can configure the browser in such a way that the cookie persists, even if it's expired. Setting the value as described above would solve this problem.
这篇关于服务器端删除cookies的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!