access control layer on events for socket.io? #3899
-
Hello everyone! I would like to ask for suggestions/considerations about using a sort of access control layer with socket.io. I'm wondering if there are correct patterns, if it's an anti-pattern or if my idea will do. A little bit of context Role2's clients may represent anonymous clients. They can, with a special random code, retrieve from the server a special JWT which allow them to authenticate on the socket.io server. Role2 must not play the Role1 part, so I need a way to control what a role2 client can do. my idea
I would like to know if my approach is valid or if there are better approach. Thanks in advance! 😄 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi! There are a few possible solutions:
io.on("connection", (socket) => {
if (socket.role === "role1") {
socket.on("action1", () => { /* ... */ }
}
if (socket.role === "role2") {
socket.on("action2", () => { /* ... */ }
}
}); Pros: no additional check in the event handler
io.on("connection", (socket) => {
socket.use(([event], next) => {
if (isAuthorized(socket, event)) {
next();
}
// skip the packet (or call socket.disconnect(), depending on your use case)
});
}); Documentation: https://socket.io/docs/v4/server-socket-instance/#Socket-middlewares Pros:
Cons: none?
io.on("connection", (socket) => {
// event handlers for role2
});
io.of("/authorized-zone", (socket) => {
// event handlers for role1
}); Documentation: https://socket.io/docs/v4/namespaces/ Pros:
Cons:
|
Beta Was this translation helpful? Give feedback.
Hi! There are a few possible solutions:
Pros: no additional check in the event handler
Cons: the role must be static (no update during the session)
Documentation: https://socket.io/docs/v4/server-socket-i…