2

Recently I started learning socket.io at work and I got the general concept of emitting events and listening to events. Currently I'm building a simple chat app with Node.js, Express and Socket.io and I want to add authentication to my app, so that on page refresh, the data is saved and the connection is retained.

I read a lot about token-based authentication vs cookie based authentication and I understood that in most cases it's better to use token based authentication strategy.

I found a lot of npm packages regarding this topic that help authenticate requests but I can't find one simple way of implementation for simple authentication.

My question is: What is the best/correct way of implementing authentication with sockets?

If you guys could help me with this issue, I'd really appreciate it.

David Lasry
  • 829
  • 3
  • 12
  • 31
  • You don't have a single question in your "question". Can you clearly state what do you want to know? And maybe explain or show some code as to how far you are and where did you get stuck? – Zlatko Feb 23 '18 at 13:31
  • I've used Express JWT https://github.com/auth0/express-jwt in the past and it does a great job. – t3__rry Feb 23 '18 at 13:34
  • 1
    @Zlatko My question is What is the best/correct way of implementing authentication with sockets? – David Lasry Feb 23 '18 at 13:38
  • @t3__rry How can I use this package with Socket.io? – David Lasry Feb 23 '18 at 13:38
  • @DavidLasry the one I provided is for Express. Take a look at this thread https://stackoverflow.com/questions/36788831/authenticating-socket-io-connections and this package: https://github.com/auth0-community/socketio-jwt – t3__rry Feb 23 '18 at 13:48

1 Answers1

2

When the client connects to the server, make it a requirement to send an 'authentication' event to the server with the token, if the user doesn't send this event within 5 seconds then disconnect them, if the token is invalid then disconnect them, only allow them to stay connected if they have a valid access token.

Also ensure they send this token up each time they make a request to the server & validate it, not 100% necessary because they wouldn't have been able to connect in the first place without a valid token but it wouldn't hurt.

Alex Catchpole
  • 7,156
  • 6
  • 20
  • 29