WebSocket connections face unique security challenges that differ from
traditional HTTP requests. This comprehensive guide covers all aspects of
securing WebSocket implementations, from preventing common attacks to
implementing robust authentication and rate limiting.
Cross-Site WebSocket Hijacking occurs when a malicious website establishes a
WebSocket connection to your server using a victim’s credentials (cookies).
Unlike traditional CSRF, WebSocket connections can maintain persistent
bidirectional communication.
CSWSH is an attack where a malicious website opens a WebSocket
connection to a target server using the victim’s browser cookies.
Prevent it by validating the Origin header during the handshake and
using CSRF tokens or custom headers that cross-origin requests
cannot set.
Should I use WSS (WebSocket Secure) in production?
Yes, always. WSS encrypts the connection with TLS, preventing
eavesdropping and man-in-the-middle attacks. Most browsers and
proxies handle WSS more reliably than plain WS. Configure TLS 1.2+
with strong cipher suites.
Pass a JWT or session token during the initial HTTP upgrade
handshake, either as a query parameter or in cookies. Validate the
token server-side before accepting the connection. For long-lived
connections, implement token refresh over the WebSocket itself.
Limit both new connections and messages per connection. Track
connection counts per IP and per authenticated user. Implement a
token bucket or sliding window algorithm for message rate limiting.
Disconnect clients that exceed limits.