Web socket authentication with nodejs, socket.io & Angular

Prabath Perera
Databox Technologies
3 min readMar 24, 2020
Background vector created by freepik — www.freepik.com

Web socket, nodejs and socket.io are 3 of top topics/ buzz words. So you’d expect lots of articles, how to’s and guides on this. Surprisingly it seems not. I’m new to all three and wanted them for a project. So as usual to figure out best practices and common patterns I started searching. Apart from few hint in the direction articles and stuff I barely found anything.

So I’ve figured out things on my own and converged on two best possible methods per my opinion.

  1. Authenticate on connecting using query param
  2. Authenticate after connecting

Both have pros and cons of their own. Will get to that later after doing some perf as well.

I’ll walkthrough both methods using a angular 9 client as well. I assume you have basic knowledge on all these topics, if not you can refer the complete github code for more clarity.

I’m using Typescript for nodejs application as well.

1. Authenticate on connecting using query param

Below is the code snippet (ChatService)

chat.service.ts

Line 5: I have a separate auth service which does the temporary ws token validation. After my application authenticates, Its create short lived (<5min)access token for web socket authentication. For additional security you can bind IP address to the token also. This token is used in the query param when initiating web socket connection.

I use below code snippet to initiate web socket connection on Angular end.

const socket: Socket= new Socket({ url: `http://localhost:3000?token=${tokenData.token}`, options: {} });

Line 9/10: Inside the constructor I setup onConnection and onDisconnect handlers. onConnection is where the magic happens.

Line 15–23: Inside on connection if socket.conn.request._query[‘token’] is specified, user is authenticated using token and start listening to socket messages.

Line 25: If token is not specified, connection is immediately terminated

Line 32–35: This function setup message listener for specific socket and stores the connection in a dictionary for later communications.

That’s it. It’s simple and straightforward. However it’s bad practice and insecure to use security tokens in the URL. They are logged/ monitored by many intermediates. So avoid them much as possible.

Sending the token in the header is a option. But per my knowledge headers only works if polling as transport (https://socket.io/docs/client-api/#With-extraHeaders). I don’t want to restrict myself like that. Do you?

2. Authenticate after connecting

This is the interesting approach. What we do here is,

  1. When client connects, we add it to a pending queue and schedule a auth grace period. Client should authenticate within this grace period. However until authenticate server will neither listen or response to any other events.
  2. Once connection is established, client sends an auth request with the token. Server then validates the token and start listening to socket events (messages).
  3. If client fails to authenticate within the grace period server terminates the connection.

Refer below code snippet

The code is mostly self explanatory. Key to notice,

Line 21–27: Setting grace period for auth by utilizing setTimeout

Line 30: Listen for ‘auth’ event

Line 46–55: Authenticate once user submits a token.

Line 36–39: Function to start listening to client event

Also notice that Im using 2 dictionaries to store authorized sockets and pending sockets. These are not essential. So shape per your requirement.

You can find entire code for this discussion along with below functionalities from the git hub.

  • Typescript nodejs project (it was actually bit challenging to set this off even with the template I used)
  • Google auth configured Angular/ Ionic
  • JWT Token for http authentication

Finally, Im just getting into writing articles and I expect to publish the journey of learning as I learn different technologies. So please leave any pointers if there’s nay.

Don’t forget to clap if you like the article. Keeps me motivated. 🙂

--

--