无法使用 websockts 和 socket.io 从 cookie 获取连接的会话 ID
在socket.io服务器的配置中,我有以下代码,它从标头中的cookie中获取会话id,我想验证会话是否与登录的用户相对应(我使用express作为http服务器,并且用于存储会话的 MemoryStore)。
io.set('authorization', function (handshakeData, callback) {
var cookies = handshakeData.headers.cookie;
cookies = connect.utils.parseCookie(cookies);
var sid = cookies['connect.sid'];
/* verify that is a valid session */
});
当我从 Firefox 连接到我的 node.js 时,这有效,最终使用长轮询,但当我从使用 WebSockets 的 Chrome 连接时失败。它不起作用的原因是当客户端代码连接到套接字时,Chrome 根本不会在标头中发送 cookie。
有没有办法让 Chrome 通过 WebSockets 发送 cookie?
如果不是,我应该如何存储 sessionID 以便在验证套接字连接时可以访问它?
我还应该注意到,保存会话 ID 的 cookie 设置为仅 http,我在其他地方看到过这可能是问题所在?我的理解是,删除该选项会增加您遭受 XSS 攻击的脆弱性吗?
感谢您的帮助!
In the configuration of a socket.io server I have the following code which grabs the session id from the cookie in the header and I want to verify that session corresponds with a logged in user (I'm using express as the http server, and a MemoryStore to store sessions).
io.set('authorization', function (handshakeData, callback) {
var cookies = handshakeData.headers.cookie;
cookies = connect.utils.parseCookie(cookies);
var sid = cookies['connect.sid'];
/* verify that is a valid session */
});
This works when I connect to my node.js from Firefox which ends up using long-polling, but fails when I connect from Chrome which uses WebSockets. The reason it doesn't work is Chrome doesn't send a cookie in the header at all when the client code connects to the socket.
Is there anyway to get Chrome to send the cookie over WebSockets?
If not how should I store the sessionID so that it can be accessed when authenticating a socket connection?
I should also note that the cookie keeping the session id is set to http-only, which I've seen elsewhere could be the problem? My understanding is that be removing that option increases your vulnerability to XSS attacks?
Thanks for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不熟悉 Chrome 的特定行为。然而,很难保证你会得到像 Flash 套接字这样的 cookie,socket.io 可能会依赖它。
但是,您可以在连接时使用 https 之类的内容通过 socket.io 手动发送会话 ID ://github.com/carhartl/jquery-cookie 或者只是通过 javascript 访问 cookie(例如 document.cookie)。无论交通如何,您都可以保证以这种方式获得它。
Not familiar with that particular behavior of Chrome's. However, its pretty hard to guarantee that you're going to get a cookie with things like Flash sockets, which socket.io may fall back on.
You could, however, send the session id manually over the wire with socket.io when you connect, using something like https://github.com/carhartl/jquery-cookie or just plain accessing the cookie via javascript (e.g. document.cookie). You'd be guaranteed to have it that way, regardless of transport.
尝试在客户端上禁用 Flash 套接字和 Web 套接字:
Try disabling flash sockets and web sockets on your client: