我正在尝试为 WebSockets 设置 NodeJS + Socket.IO。套接字部分工作正常,但显然,我们需要安全性,因此我找到了一些指南,其中显示了如何设置 Socket.IO 中间件,该中间件应该首先验证所有套接字。这是我到目前为止的代码:
var socketio = require('socket.io');
var cookie = require("cookie");
var cookieParser = require("cookie-parser");
var server = http.createServer(app).listen(port);
var io = socketio.listen(server);
// This is the middleware which supposed to check the session cookie
io.use(function (socket, next) {
var handshakeData = socket.request;
if (handshakeData.headers.cookie.indexOf('connect.sid') > -1) {
handshakeData.cookie = cookie.parse(handshakeData.headers.cookie);
handshakeData.sessionID = cookieParser.signedCookie(handshakeData.cookie['connect.sid'], 'foobar');
if (!handshakeData.sessionID) {
next(new Error('Cookie is invalid.'));
}
} else {
next(new Error('No cookie found.'));
}
next();
});
var namespaced = io.of('/socket/test');
namespaced.on('connection', function (socket) {
console.log('a user connected to /socket/test');
socket.on('fetch', function (args) {
// The unauthenticated browser still executes this next line!
namespaced.emit('you got some data!');
});
});
问题是,中间件逻辑似乎很好。我已经使用经过身份验证的浏览器和未经身份验证的浏览器进行了尝试。未经身份验证的浏览器正确返回 next(new Error('some error'))
,这就是文档所说的您应该处理身份验证的方式 - http://socket.io/docs/server-api/#namespace#use(fn:function):namespace
但是,尽管身份验证中间件返回错误,套接字仍然被允许并且客户端接收数据。
仅供引用,我正在 Node 0.10.24 之上运行 Socket.IO 1.3.6(最新)。
最佳答案
您始终在中间件末尾调用next
。当在错误中使用 next
时,您需要执行 return next(new Error(...));
,否则最后的 next
将始终被执行。
关于node.js - Socket.IO 身份验证逻辑似乎有效,但无论如何都允许未经身份验证的套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31876561/