Skip to content

access control layer on events for socket.io? #3899

Answered by darrachequesne
vincesempre asked this question in Q&A
Discussion options

You must be logged in to vote

Hi! There are a few possible solutions:

  • registering handlers depending on the role
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
Cons: the role must be static (no update during the session)

  • using a socket middleware
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-i…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@vincesempre
Comment options

Answer selected by vincesempre
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants