I'm using the Socket.io use function (https://socket.io/docs/server-api/#namespace-use-fn) to authenticate connections, but I'm not sure if I can disconnect a socket from within that function, because I don't know if the connection is made prior to calling 'use'.
Does Socket.io wait until the completion of io.use
before making the connection? If the authentication fails, how can I stop the connection from being made?
My testing has shown that io.on('connection')
is not fired until next()
is called within the 'use' function. But I've also found that when I include socket.disconnect()
inside of the 'use' function, the client will in fact disconnect, but the server still thinks the client is connected, as shown by io.clients
.
I've read this SO question which cleared up some details about the 'use' function but didn't address my question: Socket.IO middleware, io.use
io.use(function (socket, next) {
let token = socket.handshake.query.token;
if (verify(token) == false) {
socket.disconnect(); // Can I do this here?
}
next();
});
// This isn't fired until the above 'use' function completes, but
// despite disconnecting above, 'on connection' still fires and `io.clients` shows the client is connected
io.on('connection', function (socket) {
setTimeout(function(){
// Get number of connected clients:
io.clients((error, clients) => {
if (error) throw error;
console.log(clients); // => [PZDoMHjiu8PYfRiKAAAF, Anw2LatarvGVVXEIAAAD]
});
}, 2000);
});
EDIT
I have mostly found the answer to this through testing. next()
should only be called if the authentication succeeds. If it fails, just don't call next()
and the socket will not connect. However, I do not understand why calling socket.disconnect()
inside of the 'use' function creates a scenario where the server thinks it's connected to the client, but the client is actually disconnected.