socketio / socket.io-admin-ui

Admin UI for Socket.IO
https://admin.socket.io
MIT License
346 stars 94 forks source link

Feature request - callback for authentication #45

Closed Thomas-1985 closed 2 years ago

Thomas-1985 commented 2 years ago

Hi

I have embedded the ui in my app which features a role-based authentication (roles "user" and "admin"). As there are more then one user which should have the ability to connect to the ui, is there a callback or similar i can use for authentication?

I thought about connecting the ui to my userRole so that only users with userRole.admin can connect (if they authenticate correctly).

Best, Thomas

darrachequesne commented 2 years ago

Hi! I think you should be able to use a classic middleware:

io.of("/admin").use((socket, next) => {
  const userRole = fetchRole(socket);

  if (userRole.admin) {
    next();
  } else {
    next(new Error("forbidden"));
  }
});

Reference: https://socket.io/docs/v4/middlewares/

Thomas-1985 commented 2 years ago

Ok an what do i have to do to the instrument method then? Currently what i use for initialization is

    instrument(this.socketServer, {
      auth: {
        type: "basic",
        username: "admin",
        password: "$2a$10...."
      },
      readonly: true,
      namespaceName: "/socketui"
    });

and then for the socket namespace for the ui

io.of("/socketui").use((socket, next) => {
  const userRole = fetchRole(socket);

  if (userRole.admin) {
    next();
  } else {
    next(new Error("forbidden"));
  }
});

Correct?

darrachequesne commented 2 years ago

@Thomas-1985 yes, that should work. And if you don't want the user/password authentication, you can use auth: false:

instrument(this.socketServer, {
  auth: false,
  readonly: true,
  namespaceName: "/socketui"
});
Thomas-1985 commented 2 years ago

Yes it works fine, thanks a lot! :)