Course contentsShow
← Security
Lesson 1069 of 3,05222. Web Security - Client-Side and SPA SecurityFree lesson

WebSocket Authentication and Authorization

Securing WebSocket connections with tokens, cookies, and proper authentication during upgrade.

WebSocket Authentication and Authorization

What you'll learn: How to securely authenticate users and authorize actions when upgrading from HTTP to persistent WebSocket connections.

The Challenge with WebSocket Security

WebSocket connections start with an HTTP handshake but then "upgrade" to a persistent, bidirectional channel. Unlike REST APIs where you authenticate every request, WebSockets authenticate once during the initial upgrade—then that connection stays open. This creates a unique security challenge: if you don't authenticate properly during that brief upgrade moment, an attacker could maintain an authenticated connection indefinitely.

Think of it like entering a concert venue: REST APIs check your ticket every time you enter a door, but WebSockets check your ticket once at the gate, then you're inside for the whole show. If the gate security is weak, anyone can get in and stay.

Securing the WebSocket Upgrade

During the HTTP upgrade request, you must authenticate using:

  • Bearer tokens in headers: Authorization: Bearer <token> sent during the upgrade handshake
  • Session cookies: Leveraging existing HTTP session authentication (ensure SameSite and Secure flags are set)
  • Query string tokens (less secure): wss://example.com/socket?token=xyz — vulnerable to logging and referrer leakage

Once the connection is established, you still need ongoing authorization checks. Just because a user authenticated doesn't mean they should access every resource. Validate permissions for each message received, similar to how you'd check authorization on each API endpoint.

Never trust the client to self-police. Always verify on the server that each WebSocket message operation is authorized for that specific user.

Key Takeaway: Authenticate WebSocket connections during the HTTP upgrade handshake using tokens or cookies, but continue validating authorization for every message operation throughout the connection's lifetime—authentication happens once, but authorization must be continuous.