An HTTP request carries credentials every time. A WebSocket carries them once, at the handshake. After 101 Switching Protocols, what the server holds is a verdict, “this socket belongs to alice”, not the evidence behind it. When the token expires, is revoked, or loses permissions, the open socket does not change at all.

The Origin header checked at the handshake invites a similar misunderstanding: “we validate Origin, so only our app can connect.”

Both come from misreading what the handshake proves. All it can say is who connected with which token at that moment and, for a browser, from which page. This post shows, with a small working server, how the server keeps owning everything else.

How a browser can send the token

The browser’s new WebSocket(url, protocols) has no argument for headers, so the Authorization header is out. The cost of each place:

WhereCost
CookieAmbient authority, attached automatically. As shown below, without an Origin check another page can use it.
Query stringURLs end up in access logs and proxies.
Sec-WebSocket-ProtocolA page can set it. The server must select and echo one of the offered values, or the browser fails the connection.
First message after openThe server accepts a connection it cannot identify yet. Close it if the message does not arrive within a short deadline.

The server in this post takes ["bearer", "<token>"] as the subprotocol list and selects bearer.

Origin proves a page, not a client

Origin is what the browser says about which page opened the connection. A page’s script cannot change it. Clients other than browsers can send any value they like. RFC 6455 §10.2 says as much: the point is not to stop non-browser clients from connecting but to keep malicious JavaScript from making a trusted browser fake a handshake.

The check prevents one attack. I ran a server that authenticates with a cookie and ignores Origin, and tried it in headless Chrome 154. The victim gets a SameSite=Lax cookie at http://localhost:4100/login, then opens a page from another server (port 4200) in the same browser. That page opens ws://localhost:4100/ws.

Origin ignored        page on :4200, victim's cookie   => OPEN {"hello":"alice","origin":"http://localhost:4200"}
exact-match allowlist page on :4200, victim's cookie   => CLOSED code=1006   (server saw the Origin and sent 403)

SameSite=Lax did not stop it because ports 4200 and 4100 on localhost are cross-origin but same-site. The site check ignores the port.

In the other direction, Origin tells you nothing about non-browser clients. Claiming an allowed Origin without a token still gets a 401. The token authenticated the client, not the header.

How you compare matters too. With an allowlist of just https://app.example.com, I tried four hostile values. A comparison that looks for the host with includes let three through: https://app.example.com.evil.test, https://evil.test/?https://app.example.com and https://notapp.example.com. startsWith let the first one through. An exact match against a Set rejected all four, including the string null. The origin a browser sends has no path and no trailing slash, so an exact match is enough.

The rule has two steps. If Origin is present, it must match the allowlist exactly. Present or not, require a credential the browser does not attach on its own.

// The handshake rule: Origin must match exactly when present; a token is always required.
export function gate({ origin, token, allowed, revoked }) {
  if (origin !== undefined && !allowed.has(origin)) return { status: 403 };
  const claims = verify(token);
  if (!claims || revoked.has(claims.jti)) return { status: 401 };
  return { status: 101, claims };
}

A request without Origin comes from something other than a browser, so it is not refused. The token alone decides.

The page never hears why it was refused

Refuse a handshake with a 401, and the page’s script cannot see the reason. The WHATWG spec keeps scripts from telling apart servers that did not complete the handshake, because otherwise a page could probe the user’s local network. What headless Chrome 154 reported:

Server behavioropenedclose codereason
Selects bearer, closes with 4401 after openyes4401token expired
Does not select a subprotocolno1006(empty)
Answers the upgrade with HTTP 401no1006(empty)

A refused handshake and a network failure both look like 1006 to the page. So when a client sees 1006, it refreshes its token once and retries once, then backs off. If you want the page to know “expired”, accept the connection first and then close it with a code from the private-use range (4000 to 4999). The 4401 and 4403 here come from that range.

The server enforces expiry

A token and a socket can drift apart in three ways: expiry, revocation and a change in permissions. Only expiry is known in advance, and a server timer can handle it.

The simplest approach is for the server to close at expiry and the client to reconnect with a new token. If reconnecting is expensive, accept a new token on the same socket. Either way, the server needs the same four rules:

  1. The server enforces the deadline. It sends reauth shortly before expiry and closes at expiry if nothing arrives.
  2. The subject cannot change. Someone else’s valid token is not a renewal for this socket.
  3. The scope cannot widen. Narrowing applies immediately.
  4. The lifetime cannot shrink. An older token does not move the expiry back.
// Renewal rules: same subject, never widen the scope, never shorten the lifetime.
function accept(ws, c) {
  if (revoked.has(c.jti) || c.sub !== ws.claims.sub) return false;
  if (!c.scope.every((s) => ws.claims.scope.includes(s))) return false; // more rights need a fresh handshake
  ws.claims = { ...ws.claims, scope: c.scope, exp: Math.max(ws.claims.exp, c.exp) }; // narrow now; extend, never shorten
  arm(ws);
  return true;
}

// The server, not the client, enforces the deadline: ask shortly before, close at expiry.
function arm(ws) {
  clearTimeout(ws.warn); clearTimeout(ws.kill);
  const left = ws.claims.exp - Date.now();
  ws.warn = setTimeout(() => ws.readyState === 1 && ws.send(JSON.stringify({ type: "reauth" })), Math.max(0, left - leadMs));
  ws.kill = setTimeout(() => ws.close(CLOSE_EXPIRED, "token expired"), left);
}

The client’s clock may be wrong, so the server is the one that prompts. And whatever step fails, the server closes at expiry and the client reconnects. Because reconnecting is always the fallback, renewing on the same socket is an optimization rather than a new way to break. Renewing over HTTP by naming the connection also works, but the request has to reach the node that holds the socket, and this post leaves it out.

With 500 ms tokens, each strategy ran for 2.6 seconds:

reconnect  connections=6  closes with 4401=5  ticks received=20
in-band    connections=1  closes with 4401=0  ticks received=25

With reconnects, the server closed with 4401 five times and the client opened six connections. Renewing in band kept one connection. The reconnect run received fewer ticks because anything sent while it was reconnecting was missed. If you rely on reconnecting, you need a resume mechanism that replays what happened in between.

Revocation does not take effect until expiry

The server does not learn about revocation or permission changes unless someone tells it. This test asserts the bad behavior on purpose:

test("revocation does not cut off an open connection before it expires", async () => {
  const old = mint("alice", 600);
  const ws = await connect(old);
  revoked.add(verify(old).jti);
  await sleep(200);
  assert.equal(ws.readyState, WebSocket.OPEN);        // nothing re-checks revocation by itself
  assert.equal(await ws.closed, CLOSE_EXPIRED);       // it ends at expiry: the worst-case delay
});

Revoke the token, and the open socket lives until expiry. Renewal can only cap the delay at the remaining lifetime. If “log out of all devices” has to take effect in seconds, shorten lifetimes, or give the revoking side a path to close that subject’s sockets.

Which to use

  • Connections last a few minutes. Authenticate at the handshake, close at expiry and let the client reconnect. Build no renewal mechanism.
  • Reconnecting is cheap, or a resume path already exists. Close at expiry and reconnect. It is the simplest option and always the fallback.
  • Sockets routinely outlive tokens and reconnecting is expensive. Renew on the same socket.
  • Revocation must take effect in seconds. Build a path that pushes a disconnect, not a renewal.

Common mistakes

  • Comparing Origin by substring or prefix. Look-alike domains get through.
  • Allowing null or wildcards. A sandboxed iframe sends Origin: null. Forgotten subdomains get through.
  • Refusing every request without Origin. Your own native apps and scripts stop working. Decide by token.
  • Checking after the upgrade. Closing on the first message is too late, the server has already sent data. Refuse with HTTP before handleUpgrade.
  • Letting the client pick when to renew. With a skewed clock it renews late or repeatedly.
  • Allowing a renewal to change the subject or widen the scope. That extends someone else’s socket or silently escalates privileges.
  • Using renewal in place of revocation. Revocation still waits for expiry.

Try it

It runs on Node.js 20 with ws 8. After npm i ws@8, save the files below and run node --test auth.test.mjs and node demo.mjs.

token.mjs (a toy signed token for illustration)
// A toy signed token: base64url(JSON claims) + "." + HMAC. Illustration only; use a real JWT/PASETO library in production.
import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
const SECRET = "demo-secret";
const b64 = (s) => Buffer.from(s).toString("base64url");
const sign = (p) => createHmac("sha256", SECRET).update(p).digest("base64url");

export const mint = (sub, ttlMs, scope = ["read"]) => {
  const p = b64(JSON.stringify({ sub, scope, exp: Date.now() + ttlMs, jti: randomUUID() }));
  return `${p}.${sign(p)}`;
};
export const verify = (token) => {
  const [p, s] = String(token).split(".");
  if (!p || !s || s.length !== sign(p).length || !timingSafeEqual(Buffer.from(s), Buffer.from(sign(p)))) return null;
  const claims = JSON.parse(Buffer.from(p, "base64url"));
  return claims.exp > Date.now() ? claims : null;
};
server.mjs
// Authenticate at the handshake, then keep authorizing for the life of the connection.
import http from "node:http";
import { WebSocketServer } from "ws";
import { verify } from "./token.mjs";

export const CLOSE_EXPIRED = 4401, CLOSE_FORBIDDEN = 4403; // 4000-4999: private use (RFC 6455 section 7.4.2)

// The handshake rule: Origin must match exactly when present; a token is always required.
export function gate({ origin, token, allowed, revoked }) {
  if (origin !== undefined && !allowed.has(origin)) return { status: 403 };
  const claims = verify(token);
  if (!claims || revoked.has(claims.jti)) return { status: 401 };
  return { status: 101, claims };
}

export function startServer({ allowed = new Set(), revoked = new Set(), leadMs = 150 } = {}) {
  const wss = new WebSocketServer({ noServer: true, handleProtocols: () => "bearer" });
  const server = http.createServer((req, res) => res.writeHead(404).end());

  server.on("upgrade", (req, socket, head) => {
    const [, token] = String(req.headers["sec-websocket-protocol"] ?? "").split(/,\s*/); // ["bearer", "<token>"]
    const g = gate({ origin: req.headers.origin, token, allowed, revoked });
    if (g.status !== 101) {
      socket.end(`HTTP/1.1 ${g.status} ${http.STATUS_CODES[g.status]}\r\nContent-Length: 0\r\n\r\n`);
      return;
    }
    wss.handleUpgrade(req, socket, head, (ws) => {
      ws.claims = g.claims;
      ws.on("close", () => { clearTimeout(ws.warn); clearTimeout(ws.kill); });
      ws.on("message", (raw) => {
        let m; try { m = JSON.parse(raw); } catch { return ws.close(1008); }
        if (m.type !== "auth") return;
        const c = verify(m.token);
        if (!c || !accept(ws, c)) ws.close(CLOSE_FORBIDDEN, "renewal rejected");
      });
      arm(ws);
      wss.emit("ready", ws);
    });
  });

  // Renewal rules: same subject, never widen the scope, never shorten the lifetime.
  function accept(ws, c) {
    if (revoked.has(c.jti) || c.sub !== ws.claims.sub) return false;
    if (!c.scope.every((s) => ws.claims.scope.includes(s))) return false; // more rights need a fresh handshake
    ws.claims = { ...ws.claims, scope: c.scope, exp: Math.max(ws.claims.exp, c.exp) }; // narrow now; extend, never shorten
    arm(ws);
    return true;
  }

  // The server, not the client, enforces the deadline: ask shortly before, close at expiry.
  function arm(ws) {
    clearTimeout(ws.warn); clearTimeout(ws.kill);
    const left = ws.claims.exp - Date.now();
    ws.warn = setTimeout(() => ws.readyState === 1 && ws.send(JSON.stringify({ type: "reauth" })), Math.max(0, left - leadMs));
    ws.kill = setTimeout(() => ws.close(CLOSE_EXPIRED, "token expired"), left);
  }

  return { server, wss };
}
auth.test.mjs (seven tests)
import assert from "node:assert/strict";
import { test, before, after } from "node:test";
import WebSocket from "ws";
import { mint, verify } from "./token.mjs";
import { startServer, CLOSE_EXPIRED, CLOSE_FORBIDDEN } from "./server.mjs";

const revoked = new Set();
const { server } = startServer({ allowed: new Set(["https://app.example.com"]), revoked, leadMs: 100 });
let port;
before(async () => { await new Promise((r) => server.listen(0, "127.0.0.1", r)); port = server.address().port; });
after(() => { server.close(); server.closeAllConnections(); });

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const connect = (token, origin) => new Promise((resolve, reject) => {
  const ws = new WebSocket(`ws://127.0.0.1:${port}/`, ["bearer", token], origin ? { origin } : {});
  ws.closed = new Promise((r) => ws.on("close", (code) => r(code)));
  ws.on("open", () => resolve(ws));
  ws.on("unexpected-response", (req, res) => reject(new Error(String(res.statusCode))));
  ws.on("error", reject);
});

test("Origin: allowed or absent passes, anything else is 403; the token is what admits", async () => {
  const t = mint("alice", 2000);
  (await connect(t, "https://app.example.com")).close();
  (await connect(t)).close();                                          // no Origin: a non-browser client
  await assert.rejects(connect(t, "https://evil.test"), /403/);
  await assert.rejects(connect("forged.token", "https://app.example.com"), /401/); // a spoofed Origin buys nothing
});

test("without renewal the server closes with 4401 at expiry", async () => {
  const ws = await connect(mint("alice", 300));
  assert.equal(await ws.closed, CLOSE_EXPIRED);
});

test("a valid in-band renewal keeps the connection past the original expiry", async () => {
  const ws = await connect(mint("alice", 300));
  ws.send(JSON.stringify({ type: "auth", token: mint("alice", 2000) }));
  await sleep(500);
  assert.equal(ws.readyState, WebSocket.OPEN);
  ws.close();
});

test("a token for another subject is refused", async () => {
  const ws = await connect(mint("alice", 2000));
  ws.send(JSON.stringify({ type: "auth", token: mint("bob", 4000) }));
  assert.equal(await ws.closed, CLOSE_FORBIDDEN);
});

test("a renewal cannot widen the scope", async () => {
  const ws = await connect(mint("alice", 2000, ["read"]));
  ws.send(JSON.stringify({ type: "auth", token: mint("alice", 4000, ["read", "write"]) }));
  assert.equal(await ws.closed, CLOSE_FORBIDDEN);
});

test("a stale token cannot shorten the lifetime", async () => {
  const ws = await connect(mint("alice", 2000));
  ws.send(JSON.stringify({ type: "auth", token: mint("alice", 100) }));
  await sleep(400);
  assert.equal(ws.readyState, WebSocket.OPEN);
  ws.close();
});

test("revocation does not cut off an open connection before it expires", async () => {
  const old = mint("alice", 600);
  const ws = await connect(old);
  revoked.add(verify(old).jti);
  await sleep(200);
  assert.equal(ws.readyState, WebSocket.OPEN);        // nothing re-checks revocation by itself
  assert.equal(await ws.closed, CLOSE_EXPIRED);       // it ends at expiry: the worst-case delay
});
demo.mjs (reconnect vs. renewing on the same socket)
// Reconnect at expiry vs. renew in band. Run: npm i ws && node demo.mjs
import WebSocket from "ws";
import { mint } from "./token.mjs";
import { startServer, CLOSE_EXPIRED } from "./server.mjs";

const TTL = 500, RUN = 2600; // tiny lifetimes so that the demo takes seconds
const { server, wss } = startServer({ leadMs: 150 });
await new Promise((r) => server.listen(0, "127.0.0.1", r));
const port = server.address().port;
wss.on("ready", (ws) => { ws.tick = setInterval(() => ws.readyState === 1 && ws.send(JSON.stringify({ type: "tick" })), 100); ws.on("close", () => clearInterval(ws.tick)); });
const getToken = async () => mint("alice", TTL); // stands in for your token endpoint

async function run(strategy) {
  const stats = { connections: 0, closes: [], ticks: 0 };
  let ws, stop = false;
  const open = async () => {
    stats.connections++;
    ws = new WebSocket(`ws://127.0.0.1:${port}/`, ["bearer", await getToken()]);
    ws.on("message", async (raw) => {
      const m = JSON.parse(raw);
      if (m.type === "tick") stats.ticks++;
      if (m.type === "reauth" && strategy === "in-band") ws.send(JSON.stringify({ type: "auth", token: await getToken() }));
    });
    ws.on("close", (code) => { stats.closes.push(code); if (!stop) open(); }); // every strategy falls back to reconnect
    ws.on("error", () => {});
  };
  await open();
  await new Promise((r) => setTimeout(r, RUN));
  stop = true; ws.close();
  await new Promise((r) => setTimeout(r, 50));
  return stats;
}

for (const s of ["reconnect", "in-band"]) {
  const { connections, closes, ticks } = await run(s);
  console.log(`${s.padEnd(10)} connections=${connections}  closes with 4401=${closes.filter((c) => c === CLOSE_EXPIRED).length}  ticks received=${ticks}`);
}
server.close(); server.closeAllConnections();

A handshake proves one moment

A handshake is proof of one moment. After that, the server owns the deadline, and revocation needs a path that pushes a disconnect. Check Origin by exact match as a defense for browsers, and let the token decide who is connecting.