Socket.io 中的身份验证

Authentication in Socket.io

我将尝试在 socket.io 上验证连接。

目前,用户首先通过 REST API 进行身份验证,然后,我向用户发送 JsonWebToken 以及经过身份验证的用户的用户名。当我打开客户端和服务器之间的连接后,我的计划是暂时从已连接的套接字列表中删除该套接字,以防止我在进行身份验证时在服务器之间收发数据。

在此身份验证中,我验证令牌,如果令牌有效,我将套接字的 ID 重新添加到已连接套接字列表中。唯一的问题是第一部分不起作用。我似乎无法从列表中删除套接字。

为了对此进行测试,我执行了以下操作。

io.on('connection', function(socket){
    //temp delete socket
    delete io.sockets.connected[socket.id];
    console.log(io.sockets.connected);
    socket.emit("test");
});

如您所见,我删除了套接字并发出测试事件以查看套接字是否仍处于打开状态。客户收到了不应该收到的邮件。

有人知道为什么会这样吗?

尝试使用套接字对象的断开连接方法,如下所示:

io.on('connection', function(socket){
    //temp delete socket
    socket.disconnect();

    console.log(io.sockets.connected);
    socket.emit("test");
});

更新:

例如,如果您的 HTTP 服务器给客户端一个令牌:

app.post('/api/users', function (req, res) {
  var user = {
    username: req.body.username
  };

  var token = jwt.sign(user, secret, {expiresInMinutes: 30});

  res.json({token: token});
});

然后您可以重新使用该令牌来验证您的 websocket 连接。

来自客户端(html 文件)的令牌发送代码将是:

socket = io.connect('http://localhost:4000', {
  query: 'token=' + validToken,
  forceNew: true
});

服务器(socketio)中的socketio授权码为:

// here is being used a socketio middleware to validate
// the token that has been sent
// and if the token is valid, then the io.on(connection, ..) statement below is executed
// thus the socket is connected to the websocket server.
io.use(require('socketio-jwt').authorize({
  secret: secret,
  handshake: true
}));



// but if the token is not valid, an error is triggered to the client
// the socket won't be connected to the websocket server.
io.on('connection', function (socket) {
  console.log('socket connected');
});

请注意,express 上用于生成令牌的秘密,socketio 中间件的验证令牌上也使用了相同的令牌。

我创建了一个示例,您可以在其中看到这种验证的工作原理,源代码在这里:https://gist.github.com/wilsonbalderrama/a2fa66b4d2b6eca05a5d

将它们复制到一个文件夹中,然后 运行 使用节点 server.js 然后从浏览器访问 html 文件 URL: http://localhost:4000

但首先安装模块:socket.io、express、socketio-jwt、jsonwebtoken

socket.io 还将套接字保存在命名空间中(如果未指定,则为默认设置),您需要将其删除才能停止接收消息。

参见 this post for a step by step explanation of what you're trying to do, and this module 抽象了整个过程。