在Socket.io中进行身份验证

Ale*_*ole 7 sockets node.js 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");
});
Run Code Online (Sandbox Code Playgroud)

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

有谁知道为什么会这样?

Wil*_*son 9

尝试使用socket对象中的disconnect方法,如下所示:

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

    console.log(io.sockets.connected);
    socket.emit("test");
});
Run Code Online (Sandbox Code Playgroud)

更新:

例如,如果您的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});
});
Run Code Online (Sandbox Code Playgroud)

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

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

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

并且服务器(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');
});
Run Code Online (Sandbox Code Playgroud)

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

我已经创建了一个示例,您可以看到这种验证是如何工作的,源代码在这里:https://gist.github.com/wilsonbalderrama/a2fa66b4d2b6eca05a5d

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

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