What are the possible ways to authenticate user when websocket connection is used?

Burak Dede picture Burak Dede · Dec 1, 2011 · Viewed 7.6k times · Source

Example scenario: Web based multi-user chat application through websocket connection. How can I ensure (or guarantee) that each connection in this application belongs to certain authenticated user and "can't be" exploited by false user impersonation or intervene during the connection.

by the way I am using tornado websocket on server side to implement basic chat room and already doing authentication for the non-websocket part of my app.

ps : suppose authenticated user posts what he wants and when other user open the listing page of item and automatically other user is added to list of websocket listeners what I want each user able to chat with buyer of the item individually not in a chatroom way but with one to one chat

Answer

andrewnelder picture andrewnelder · Feb 23, 2012

First and foremost, there are two things you should remember about WebSockets: (a) it's an evolving standard and (b) it is designed with the intention of working with untrusted clients.

The biggest and most important thing you should always do with WebSockets is check their origin. If the origin is mismatched, obviously you don't want to deal with that client, so ignore their requests. Additionally, make sure you're using the "wss" secured WebSocket protocol rather than the "ws" unsecured protocol. This will ensure that your messages are encrypted.

The problem with just doing this, is that this information can be spoofed. See this blog post for a quick demonstration of this.

Additional Security:

  • Try sending a salted token, having it salted/hashed and sent back and validated in the handshake phase.
  • Limit requests that happen too frequently (just like the IRC protocol). If the user has submitted 10 lines or more within the span of a second, ignore that user.
  • Do a quick spam-check (there are lots of algorithms for this) -- stick to light heuristics, otherwise it will burden your server. Things like the presence of the words "free" or "viagra". Give the user a score that represents the likelihood that they are spamming or are a bot. When that is breached, boot them from the servers.

Hope that helps! Sorry if it doesn't. This is my frist answer on StackOverflow. :P