WebSocket Security Deep Dive
Secure WebSocket connections with TLS, origin validation, authentication, and message rate limiting.
What you'll learn
- WSS (WebSocket Secure) and TLS certificate management
- Origin header validation to prevent CSWSH attacks
- Token-based authentication during handshake
- Rate limiting and message size limits
Concept
WebSocket Security Deep Dive
WebSocket connections can be vulnerable to several attacks. Security must be built in from the start.
WSS: Always Use TLS
Use wss:// instead of ws://. WSS encrypts all traffic with TLS, preventing eavesdropping and MITM. Never use ws:// in production.
Origin Validation
The browser sends an Origin header during handshake. Validate against an allowlist. Without this, any website can connect (Cross-Site WebSocket Hijacking).
Authentication
WebSocket URLs cannot carry custom headers. Authenticate via: token in query string, cookie with handshake, or auth message as first message after connection.
Rate Limiting
Malicious clients can flood messages or send huge payloads. Implement per-connection rate limiting (max 100/sec) and max message size (1MB). Drop violating connections.
Example
const ALLOWED = ['https://myapp.com']; const MAX_SIZE = 1048576;
function validateHandshake(req) {
if (!ALLOWED.includes(req.headers.origin)) return {allowed:false, reason:'Untrusted origin'};
const token = new URL(req.url, 'http://x').searchParams.get('token');
if (!token) return {allowed:false, reason:'Missing token'};
return {allowed:true};
}
class RateLimiter { constructor(max) { this.max=max; this.ts=[]; } check() { const now=Date.now(); this.ts=this.ts.filter(t=>now-t<1000); if (this.ts.length>=this.max) return false; this.ts.push(now); return true; } }
const req = {headers:{origin:'https://myapp.com'}, url:'/ws?token=abc'};
console.log(validateHandshake(req));
const rl = new RateLimiter(100);
console.log('Rate check:', rl.check());
validateHandshake checks origin and token. RateLimiter uses a sliding 1-second window. Always enforce size and rate limits.
Try it
- Hash Generator
Token-based auth uses hashes - see how secure tokens are generated.
Common mistakes
The mistake
Using ws:// instead of wss:// in production.
The fix
Unencrypted WebSocket exposes all data. Always use wss:// with valid TLS.
The mistake
Not validating the Origin header.
The fix
Any malicious website can connect without origin validation. Always check against an allowlist.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.