检查 JavaScript 中是否存在 httponly cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9353630/
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
Check if httponly cookie exists in Javascript
提问by Grofit
As the question says can you find out if a cookie exists within Javascript if it is a HttpOnly? I don't need to access the information inside of it, just know it has one.
正如问题所说,如果 cookie 是 HttpOnly,您能找出 Javascript 中是否存在 cookie 吗?我不需要访问它里面的信息,只要知道它有一个。
A little more information on the situation is that there was originally a web server which used a cookie as an authentication token, and it was set to httponly as it was not used by the client so it added to the security.
关于这种情况的更多信息是,最初有一个使用cookie作为身份验证令牌的Web服务器,并且由于客户端不使用它而将其设置为httponly,因此它增加了安全性。
However now there is a change needed where the client needs to know if it has the cookie (as the site can work without the user being logged in, but if they are logged in (the auth cookie would exist) the site needs to display certain things and hide others.
但是,现在需要进行更改,其中客户端需要知道它是否具有 cookie(因为该站点可以在没有用户登录的情况下工作,但是如果他们已登录(身份验证 cookie 将存在),该站点需要显示某些事情并隐藏其他人。
There are other security precautions in place on the web server so there is no harm in the scenario where the client has an incorrect auth cookie, but the site makes it look like they are logged in, as it would delete the cookie and reject the user.
Web 服务器上还有其他安全预防措施,因此在客户端具有不正确的 auth cookie 的情况下没有任何危害,但该站点使其看起来像是已登录,因为它会删除 cookie 并拒绝用户.
采纳答案by Mike
No. And see Rob's comments below.
不。请参阅下面的 Rob 评论。
See this, which you probably already saw - http://en.wikipedia.org/wiki/HTTP_cookie#Secure_and_HttpOnly
看到这个,你可能已经看到了 - http://en.wikipedia.org/wiki/HTTP_cookie#Secure_and_HttpOnly
An HttpOnly cookie is not accessible via non-HTTP methods, such as calls via JavaScript (e.g., referencing "document.cookie")...
HttpOnly cookie 不能通过非 HTTP 方法访问,例如通过 JavaScript 调用(例如,引用“document.cookie”)...
Edit:Removed undefined
response, I wrote a script that you may not be using :)
编辑:删除了undefined
回复,我写了一个你可能没有使用的脚本:)
回答by Eric Labashosky
You can indirectly check to see if it exists by trying to set it to a value with javascript if it can't be set, then the HTTP Only Cookie must be there (or the user is blocking cookies).
如果无法设置,您可以通过尝试使用 javascript 将其设置为一个值来间接检查它是否存在,那么 HTTP Only Cookie 必须存在(或者用户正在阻止 cookie)。
function doesHttpOnlyCookieExist(cookiename) {
var d = new Date();
d.setTime(d.getTime() + (1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cookiename + "=new_value;path=/;" + expires;
if (document.cookie.indexOf(cookiename + '=') == -1) {
return true;
} else {
return false;
}
}
[UPDATE 6 Feb 2018] This doesn't work on firefox (works on Chrome & Edge, maybe others)
[2018 年 2 月 6 日更新] 这不适用于 firefox(适用于 Chrome 和 Edge,也许其他人)