What’s the best practice to renew a token for a WebSocket connection

Quite an old question I’ve asked, so I’d be happy to share our chosen practice:

  1. Once the client gets his JWT for the first time (when the application starts), a WebSocket is opened.

  2. To authenticate the channel, we send a message that we define as part of our protocol, called authMessage which contains that JWT.

  3. The server stores this data on the socket’s instance and verifies it’s validity/expiry before sending data down the wire or receiving from the client.

  4. The token gets refreshed silently in web application minutes before it is expired and another authMessage is issued to the server (repeat from step 2).

  5. If for whatever reason it gets expired before getting renewed, the server closes that socket.

This is roughly what we have implemented in our application (without optimization) and worked really well for us.

Leave a Comment