Common authentication for all namespaces in socket.io 3 #3842
-
Hi, I'm confused about how authentication is intended to work when you have multiple namespaces in socket.io 3. We currently (with socket.io 2) use something like https://github.com/socketio/socket.io/blob/master/examples/passport-example/index.js, where we put authentication middleware on the '/' namespace. This then gets executed for every connection. But we cannot do this with socket.io 3, since sockets no longer always connect to '/'. Instead we have to add this middleware to all namespaces, which seems a bit risky. What if someone uses io.of('foo') in some part of the code, but forgets to add authentication middleware to the namespace? Everything will seem to work, except that the namespace is accessible to all. Am I missing something, or is this the best option? (I also tried the 'allowRequest' option when creating the server, but that seems to cause the client to keep trying to connect after being rejected. We also have some other things we do on every new connection, which makes this a less attractive option.) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
Thanks for raising this issue, that's indeed a change from v2 to v3. A possible workaround would be to override the const of = io.of;
io.of = (...args) => {
const nsp = of.call(io, ...args);
nsp.use(yourMiddleware);
return nsp;
} Dynamic namespaces could work too, depending on your use case: const parentNamespace = io.of(/^\/dynamic-\d+$/);
parentNamespace.use(yourMiddleware); // attached to all child namespaces |
Beta Was this translation helpful? Give feedback.
-
any update on this? I also would like to add a middleware for all namespaces. |
Beta Was this translation helpful? Give feedback.
Thanks for raising this issue, that's indeed a change from v2 to v3.
A possible workaround would be to override the
io.of
method:Dynamic namespaces could work too, depending on your use case: