T
T
TeslaCtroitel2016-08-04 16:53:52
Node.js
TeslaCtroitel, 2016-08-04 16:53:52

How to catch authorization error on custom namespace in Socket.IO 1.4.8?

UPD : for those interested , a link to the docks
Based on the requirements of a small project, I decided to use Socket.IO. I have not worked with it before, although I have known NodeJS for a long time. I wrote some code, everything works as it should, but you just need to double-check everything that is in third-party guides, because they often refer to the old version (<1.0). And at this moment there was a gag with authorization.
Authorization is implemented through middleware, all according to the current version of the official documentation:

io.use((socket, next)=>{
    var sidCookie = cookie.parse(socket.headers.cookie || '')['sid'];

    if(sidCookie === undefined){
        return next(new Error('not authorized'));
    }
    //........
});

On the client, the error is caught like this (there is nothing in the docks about this, it seems):
socket.on('error', function(error){
    if(error == "not authorized"){
        //Redirect to login page
    }
});

And everything works fine until we try to connect not to the root namespace '/', but to some of our own, let it be '/test/nsp'. The error disappears into nowhere after next(error) and the client-server continue to quietly throw heartbeats at each other. Okay, let's get into the logs on the client. It turns out that the server sent us an error and it was lost somewhere on the client.
engine.io-client: socket socket receive: type "message", data "4"not authorized"" +5ms
socket.io-parser decoded 4"not authorized" as {"type":4,"nsp":"/","data":"not authorized"} +4ms
engine.io-client: polling polling +1ms
engine.io-client: polling-xhr xhr poll +1ms
engine.io-client: polling-xhr xhr open GET: http://test.com:10480/socket.io/EIO=3&transport=polling&t=LPLiIDy&sid=FihJFgV2CDLHdmY2AAAH +0ms
engine.io-client: polling-xhr xhr data null +1ms

From this moment, dances with a tambourine and misunderstandings begin. I tried authorization middleware (again, according to the documentation) to fasten not to the root, but to the custom namespace:
io.of('/test/nsp').use((socket, next)=>{
    //........
});

The result is similar, that is, no. Who met - accomplish your goal, thanks in advance. In the meantime, I went for a tambourine and coffee, as I unearth the client code, I will unsubscribe here.
PS: Yes, I know that you can just do socket.emit('not_authorized') and catch it on the client, but this is somehow not feng shui and the devil knows what it can lead to.
PSS: Node.JS 6.3.1, Socket.IO 1.4.8 (same version client), Windows 10, Chrome 51.0.2704.103

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question