Skip to content
Get started
Bastionary › Knowledge base › Identity fundamentals

WebSocket authentication: the handshake patterns that actually work

By Bastionary · Identity fundamentals

The moment you add real-time features—live dashboards, collaborative editing, chat, presence—you hit a wall that the HTTP world never prepared you for: the browser's WebSocket API won't let you set an Authorization header. You can hand it a URL and an optional subprotocol list, and that's it. The access token you use everywhere else in your app has nowhere obvious to go. Teams solve this in a hurry, usually by shoving the token in the query string, and quietly create a security problem that shows up months later in a log file.

Why you can't just put the token in the URL

The expedient move is wss://api.example.com/ws?token=eyJ.... It works instantly, which is exactly why it's dangerous. URLs are the most-logged strings in any system: they land in your reverse proxy's access log, your CDN's logs, browser history, Referer headers, and APM traces. A long-lived access token sitting in all those places is a token waiting to be replayed by anyone with log access. The connection itself is encrypted under TLS, so the token isn't exposed on the wire—but it's exposed everywhere the URL is recorded, which is a lot of places.

There are three patterns that actually hold up. Each trades a little complexity for keeping long-lived credentials out of loggable surfaces.

Pattern 1: the ticket (short-lived, single-use)

The cleanest approach decouples "prove who you are" from "open the socket." Your client makes an ordinary authenticated HTTP request—real Authorization header, your normal token—to a small endpoint that mints a ticket: a single-use, short-TTL (seconds, not minutes) credential bound to the user. The client then opens the WebSocket with that ticket in the query string. Yes, in the URL—but now it's a value that's worthless ten seconds from now and can only be redeemed once.

// 1) authenticated HTTP call mints a ticket
app.post("/ws-ticket", requireAuth, async (req, res) => {
  const ticket = randomToken(32);
  await redis.set(`ws:${ticket}`, req.user.id, "EX", 15, "NX"); // 15s, one-shot
  res.json({ ticket });
});

// 2) client opens the socket with the short-lived ticket
const { ticket } = await (await fetch("/ws-ticket", { headers: authHeader })).json();
const ws = new WebSocket(`wss://api.example.com/ws?ticket=${ticket}`);

// 3) server redeems it exactly once at the upgrade
server.on("upgrade", async (req, socket, head) => {
  const ticket = new URL(req.url, "wss://x").searchParams.get("ticket");
  const userId = ticket && await redis.getdel(`ws:${ticket}`); // atomic read+delete
  if (!userId) return socket.destroy();                        // expired or reused
  handleUpgrade(req, socket, head, { userId });
});

The getdel is the crux: redemption is atomic, so a ticket can't be used twice even under a race. If the ticket leaks into a log, by the time anyone reads it, it's expired and already consumed.

Why the ticket beats refreshing in the URL: a ticket carries no claims and grants nothing except the right to open one socket for one user in the next few seconds. Even a perfect log capture yields an attacker nothing. Your real access and refresh tokens never go near a URL.

Pattern 2: the subprotocol header

There's a loophole in the browser API. The WebSocket constructor's second argument—ostensibly for naming subprotocols—is sent as the Sec-WebSocket-Protocol request header. That's a real header you can read server-side, so you can smuggle a token through it without touching the URL.

// client: the token rides in the subprotocol list
const ws = new WebSocket("wss://api.example.com/ws", [
  "bastionary.v1",           // a real subprotocol you support
  `bearer.${accessToken}`,   // carried in Sec-WebSocket-Protocol
]);

// server: read it from the header at upgrade
const protocols = (req.headers["sec-websocket-protocol"] || "").split(",").map(s => s.trim());
const bearer = protocols.find(p => p.startsWith("bearer."))?.slice("bearer.".length);
// validate bearer, then echo back the NON-token protocol you accepted

It keeps the token out of URLs and logs that only record the path. But be careful: the protocol strings can appear in some proxy logs too, and the spec requires the server to echo back a selected subprotocol—so echo the bastionary.v1 entry, never the bearer.* one. This pattern is popular (it's how several managed real-time services ferry tokens) but it's a mild abuse of the field. Treat it as pragmatic, not pristine.

Pattern 3: authenticate in the first message

Let the socket open unauthenticated, then require the client's very first frame to be an auth message. Until that message arrives and validates, the connection can do nothing—no subscriptions, no data, no echo.

ws.on("connection", (socket) => {
  socket.authed = false;
  const deadline = setTimeout(() => !socket.authed && socket.close(4401, "auth timeout"), 5000);

  socket.on("message", async (raw) => {
    if (!socket.authed) {
      const msg = JSON.parse(raw);
      const claims = await verifyJwt(msg.token).catch(() => null);
      if (!claims) return socket.close(4401, "unauthorized");
      socket.authed = true; socket.user = claims; clearTimeout(deadline);
      return socket.send(JSON.stringify({ type: "ready" }));
    }
    // ...normal handling, now that socket.user exists
  });
});

This keeps tokens entirely out of the handshake—no URL, no headers—and plays nicely with higher-level protocols that already have a connection-init frame. The cost is the open-but-unauthenticated window, which you must bound with a hard timeout and strict "do nothing until authed" handling, or you've built a free resource for anyone to open sockets against.

Authentication at connect is not the whole job. A WebSocket can live for hours; the token that opened it will expire long before. Decide what happens then: send a re-auth message that the client answers with a fresh token, or close the socket and let the client reconnect (with a new ticket). Doing nothing means a connection outlives the authorization that justified it—a session that can't be revoked is a session you don't control.

Don't forget authorization and origin

Knowing who connected is step one; every subscription and message still needs a can they do this check, exactly as your HTTP routes do—a connected user asking to subscribe to another tenant's channel must be refused per message. And because the handshake is an HTTP request, validate the Origin header at upgrade to blunt cross-site WebSocket hijacking; the browser will happily let a malicious page open a socket to your API and ride the user's cookies if you don't.

Real-time connections are long-lived, hard to revoke, and easy to leak credentials through—which makes them exactly the part of your stack where you want full control over how tokens are minted, scoped, and expired. When you run the identity layer yourself, issuing a two-second WebSocket ticket or validating a first-message token is a few lines against your own issuer, not a feature request. Bastionary's short-lived ticket endpoint and local JWT verification are built for every one of these handshake patterns.

Run it yourself

Bastionary is free, open-source software. Follow the quick start to have it running on your own server, or browse the releases on Git.

Get started