Socket.io – Authentication on every socket event for Session management

Issue

How to use an authentication middleware that triggers on each socket event instead of each connection?

I want to use this for session management in a react-node application. I’ll send a JWT token once a user logs in and create a new row in my sessions table in my database. But after he logs in, I want to check if he is the same person for every following events by using the mentioned middleware. The front-end client will send the token through cookies.

My sign in and sign out work over socket.io and not over HTTP.

Solution

Once connected, a socket.io connection uniquely belongs to one particular endpoint. That endpoint can’t change while the socket.io connection is connected. So, as with any TCP connection, you would typically authenticate/verify the connection when the socket.io connection first connects and from then on, you would just process incoming messages from that particular client without additional verification. This is generally how pretty much everything that uses TCP and authentication works. TCP itself has protections so that a socket can’t easily be hijacked by another endpoint mid-connection.

So, it’s unclear why or what you think you need to reverify on subsequent messages on the same connection.

With socket.io, what you get on each incoming message is the message itself. There’s no other auth credentials unless the client puts them inside the actual message in which case you can just write your own function to check the data inside the message.

If you were putting credentials in every message, you could use socket.use() to process every single incoming message and check for whatever you wanted to check for in the message.

Answered By – jfriend00

Answer Checked By – Dawn Plyler (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.