欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

express中设置cookie的httpOnly属性防御xss攻击

程序员文章站 2024-03-20 14:03:58
...

大部分是xss攻击(跨站脚本攻攻击),都是尝试在客户的浏览器中注入脚本,然后获取cookie发送到黑客指定的地址。因为服务端的session都是通过一个记录seesionId的cookie来识别的。黑客拿到了cookie, 自然就能够伪造身份,进而获取到权限。cookie的httpOnly属性意味着,浏览器中不能通过document.cookie访问到这个cookie,从而达到防御xss攻击的目的。

在express-session中,默认已经开启了cookie的httpOnly: true,原文说明如下

cookie.httpOnly

Specifies the boolean value for the HttpOnly Set-Cookie attribute. When truthy, the HttpOnly attribute is set, otherwise it is not. By default, the HttpOnly attribute is set.

但是express本身提供的cookie的api默认值却是false, 需要手动设置为true. 代码如下:

res.cookie('rememberme', '1', {httpOnly: true });