根据MDN document:
为防止跨站点脚本(XSS)攻击,JavaScript的Document.cookie API无法访问HttpOnly cookie;它们仅发送到服务器。
我找到了一种用JavaScript替换HttpOnly cookie的方案,这是ASP.NET中的PoC:
<%@Page Language="C#" %>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
if (Request["m"] == "check")
{
Response.Write("Cookie=" + Request.Cookies["C"].Value);
Response.End();
}
else
{
Response.AppendCookie(new HttpCookie("C")
{
Value = "ByServer",
HttpOnly = true
});
}
}
</script>
<html>
<body>
<div>
document.cookie -> <span id=t></span>
</div>
<script>
document.getElementById("t").innerHTML = document.cookie;
document.cookie="C=ByClient";
</script>
<a href="?m=check">Check Cookie</a>
</body>
</html>
在Chrome的测试中,读取document.cookie并不能证明HttpOnly cookie确实对JavaScript不可读。但是通过设置document.cookie =“ C = ByClient”,可以同时存在两个具有不同路径的cookie。
然后从服务器端检查cookie,Request.Cookies [“ C”]返回JavaScript给出的“ ByClient”,而不返回服务器分配的“ ByServer”。客户端仅覆盖HttpOnly cookie。
如果我们设置确切的HttpCookie.Path,结果将有所不同:
Response.AppendCookie(new HttpCookie("C")
{
Value = "ByServer",
HttpOnly = true,
Path = "/asp/httponlycookie"
});
现在document.cookie =“ ByClient”无法添加或更改cookie,HttpOnly cookie受保护。
我能否得出一个结论:HttpOnly属性仅保证cookie无法被JavaScript读取,因此HttpOnly cookie仍然可以被JavaScript替换或覆盖吗?