Question

On sockjs github page written - cookies cannot be used for user authentication. Where I can read about methods to authenticate user in sockjs, it desirable with example. I don't want use socket.io.

Was it helpful?

Solution

You could use a token based approach with redis and sockjs. On a high level the process could work like this:

  1. The client first requests a token (implemented as a uuid) from the server via a regular HTTP request. This routes the request through express's middleware and gives easy access to the cookie and all of the session data.
  2. When the token is generated it is stored in redis as a key-value pair where the token is the key and the session data is the value.
  3. The token is then passed back to the user which the sockjs client appends to the url as a GET parameter when making the initial connection "upgrade" request.
  4. When the sockjs server receives the authorization request instead of verifying the cookie it parses the url, pops off the token, and attempts to query redis for the key-value pair keyed by the token. If the redis query fails or returns null data then you deny the authorization request. If the redis request succeeds then you have full access to all of the session data and now you can delete the key-value pair in redis.

A possible gotcha here is that you need to ask for a new token on every connection request. Otherwise it attempts to use the same token. If you delete tokens after validating them once this will prevent sockets from reconnecting. Depending on your application this may be the desired behavior. It was for ours so we left it as is, but it's still something worth knowing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top