Socket.io 中的身份验证

2024-02-11

我将尝试验证 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");
});

UPDATE:

例如,如果您的 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 https://gist.github.com/wilsonbalderrama/a2fa66b4d2b6eca05a5d

将它们复制到文件夹中并使用 Node 运行 server.js,然后通过浏览器访问以下 URL 的 html 文件:http://本地主机:4000 http://localhost:4000

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Socket.io 中的身份验证 的相关文章

随机推荐