Socket.IO身份验证逻辑似乎有效,但无论如何都允许使用未经身份验证的套接字

时间:2015-08-07 11:24:21

标签: node.js websocket socket.io

我正在尝试为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(最新版本)。

1 个答案:

答案 0 :(得分:0)

您总是在中间件的末尾调用next。在错误上使用return next(new Error(...));时,您需要next,或者最后next将始终执行。