简体   繁体   中英

socket.io room authorisation

I have a use case of socket.io where, within an individual namespace, a client can connect to several rooms. A user needs to authenticate on a per-room basis (because they may not be allowed to access those data streams).

Obviously I can check the authorisation on connection to the namespace using a middleware function and some auth data, but unless those rooms are already in socket.rooms when the connection is initiated, I do not know how to check, when a socket joins a room, whether or not it is authorised and subsequently force it to leave the room if it is not authorised.

Is there a join event or equivalent way of doing this? Like the connection event for a namespace but for a room.

EDIT

Having read through the source for socket.io , it appears that no events are triggered when a socket joins a room, but I might have misunderstood something: on reading the source of socket.io-client , joining rooms isn't inherent in the system, suggesting that this is only something that can be triggered on the server side. In that case, I'm assuming I have to manage the client's joining of rooms myself? If this is true, then I can just have something like:

socket.on('join', function(data) { ... });

so that when a socket wants to listen to a particular data stream, it just emit sa "join" event, with some data on which room it wants to join, and I handle the whole thing on the server?

Joining a room can only be done on the server. The client typically sends an application-specific message to the server that indicates to your app that they want to join a specific room and then the server carries out that operation on the user's behalf if the request is valid.

So, all you have to do is route all your code on the server that could join a room through one particular function that can do whatever authentication you want to do. For example, you could simply create a function that was the only way your server code would ever put a socket into a room:

function joinAuth(socket, room) {
    // can do anything you want here before actually joining the room
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM