node.js - Socket.io 中的身份验证

标签 node.js sockets socket.io

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

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

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

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

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

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

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

最佳答案

尝试使用 socket 对象的 disconnect 方法,像这样:

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

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

更新:

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

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});
});

然后您可以重用该 token 来验证您的 websocket 连接。

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

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 上用于生成 token 的 secret ,在 socketio 中间件的验证 token 上也使用了相同的 token 。

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

将它们复制到一个文件夹中并使用 node 运行 server.js,然后通过浏览器访问此 URL 中的 html 文件:http://localhost:4000

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

关于node.js - Socket.io 中的身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30814330/

相关文章:

javascript - SOCKET.IO - 在两个不同浏览器中同一登录用户使用socket.id

html - 从 Mongoose 查询数据并显示在html页面上

node.js - 部署机器人而不在 azure 上托管

sockets - Erlang:使用 sockets/gen_tcp 连接到 API

c - 意外的 getnameinfo() 主机名

html - 从 SerialPort 发送数据到 socket.io

javascript - 主机Socket.IO离线

javascript - 如何使用 Webpack 在 JavaScript 中导入 Frontmatter 和 Markdown

node.js - 以对象作为参数的 Google Node.js SDK v2 : conv. Ask() 上的操作

python - 如何在此服务器中实现 Websocket 握手?