【问题标题】:Socket.IO authentication logic seems to work, but unauthenticated socket is allowed anywaySocket.IO 身份验证逻辑似乎有效,但无论如何都允许未经身份验证的套接字
【发布时间】:2015-10-30 19:54:29
【问题描述】:

我正在尝试为 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

但是尽管认证中间件返回错误,socket仍然被允许并且客户端接收数据。

仅供参考,我在节点 0.10.24 之上运行 Socket.IO 1.3.6(最新)。

【问题讨论】:

    标签: node.js websocket socket.io


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-15
      • 2012-12-09
      • 1970-01-01
      • 2012-02-04
      • 2013-01-02
      • 2015-10-12
      • 1970-01-01
      • 2019-06-14
      相关资源
      最近更新 更多