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

WebSocket Protocol and Security Model

Understanding WebSocket handshake, framing, origin headers, and differences from HTTP security.

WebSocket Protocol and Security Model

You'll learn: How WebSockets differ from HTTP and what security considerations emerge from their persistent, bidirectional connection model.

WebSockets provide a full-duplex communication channel over a single TCP connection, allowing real-time data exchange between browser and server. Unlike HTTP's request-response pattern, WebSockets maintain an open connection where both sides can send messages independently—think of it like a phone call versus traditional mail.

The WebSocket Handshake

WebSockets start with an HTTP upgrade request. The browser sends headers including Origin (identifying the requesting page) and Sec-WebSocket-Key (a random value). If the server accepts, it responds with an HTTP 101 status and Sec-WebSocket-Accept header containing a hash of the key. This handshake authenticates the connection and prevents basic MITM attacks.

GET /chat HTTP/1.1
Host: example.com
Origin: https://example.com
Upgrade: websocket
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==

Key Security Differences from HTTP

Origin Enforcement: Servers must validate the Origin header during handshake to prevent unauthorized cross-origin connections. Unlike CORS-protected fetch requests, WebSockets don't have automatic browser-enforced restrictions—the server must explicitly check origins.

No Automatic Protections: WebSockets bypass many browser security mechanisms. There's no automatic CSRF protection, no Content Security Policy enforcement on messages, and cookies are sent automatically during handshake (enabling session hijacking if not properly secured).

Persistent Connection Risks: Once established, WebSockets remain open, creating a larger attack window. Message framing must be handled securely to prevent injection attacks within the data stream.

Key Takeaway: WebSockets require explicit server-side origin validation and can't rely on standard HTTP security mechanisms—developers must implement authentication, authorization, and input validation for every message, not just the initial handshake.