WebSocket Authentication — Realtime

The browser cannot add headers to the WebSocket handshake: there is only new WebSocket(url, protocols), and an object { headers } throws a SyntaxError. What…

With fetch, you just add an Authorization: Bearer ... header that holds a token. What about WebSocket: does new WebSocket(url, { headers: { Authorization: 'Bearer abc' } }) work?

That question is part of WebSocket authentication: making sure who is at the other end of a connection, before the server sends it anything. Its partner is authorisation: deciding which rooms it may join. Think of the back door of Mrs. Rini's Laundry, for staff only. Eko shows his staff card (the login) once at the door (the handshake), then stays inside all day (a connection that stays open). The guard, the realtime server, also sees which way he came from (the Origin header), can accept a one-time entry slip from the counter (a ticket from Laravel), and asks for the card again when the shift ends (checking again).

The browser cannot add headers

The browser's WebSocket API takes only two things: a URL and a list of subprotocols, new WebSocket(url, protocols). A subprotocol names extra message rules the client and server agree on. There is no place for headers. The second argument is taken as subprotocols, so an object { headers } is turned into the text [object Object], then refused. Tried:

Browser Result of new WebSocket(url, { headers: {...} })
Chromium 147 SyntaxError: Failed to construct 'WebSocket': The subprotocol '[object Object]' is invalid.
Firefox 146 SyntaxError: An invalid or illegal string was specified
WebKit 26.4 SyntaxError: The string did not match the expected pattern.

What the browser sends by itself in the handshake is the Origin header (the page's site address) and the cookies for the target host (the server's name). Cookies do not care about ports: tried in all three browsers, a page on http://localhost:8000 sends the localhost cookies to ws://localhost:3000. The options: a session cookie (with an Origin check), a short-lived ticket, Socket.IO's auth payload, or a token in the URL (avoid it).

Option 1: the session cookie, and an Origin check

Mrs. Rini is already logged in to Laravel on http://localhost:8000. Laravel keeps her login as a session (a login record on the server), through a cookie that goes along to the realtime server. The realtime server then asks Laravel who owns that cookie.

The danger: Cross-Site WebSocket Hijacking (taking over a WebSocket from another site): a page on another site opens a WebSocket to your realtime server, and the browser brings Mrs. Rini's cookies along. CORS does not apply to WebSockets. Tried with socket.io 4.8.4 set up with cors: { origin: ['http://localhost:8000'] }: a page from another site using transports: ['websocket'] (WebSocket only, no polling) still connected. In Firefox 146 that page connected as Mrs. Rini, because a cookie with no SameSite attribute went along. SameSite is a cookie attribute that controls whether the cookie is sent when a request comes from another site. Chromium and WebKit did not send the cookie with no SameSite from the other site, but Chromium and Firefox did send a SameSite=None cookie.

So the server has to check Origin itself:

const ALLOWED = ['http://localhost:8000']
const io = new Server(3000, {
  cors: { origin: ALLOWED, credentials: true },                            // only for HTTP polling
  allowRequest: (req, cb) => cb(null, ALLOWED.includes(req.headers.origin)), // for WebSocket too
})

Option 2: a short-lived ticket from an HTTP endpoint

A ticket is a short-lived entry pass from Laravel. The page asks Laravel for a ticket with an ordinary POST request, and the session cookie goes along. Laravel 13 checks requests like this one to stop CSRF (a request from another site that carries the user's cookie). A fetch from the same page passes that check through the Sec-Fetch-Site header, the browser's sign that the request comes from the same site. The ticket is valid for 60 seconds and can be used once.

But browsers send Sec-Fetch-Site only over HTTPS (and on localhost). If a tablet opens the laundry app at http://192.168.1.20:8000, that header is missing. Laravel then checks the CSRF token instead (a random string per session, in the page), and a ticket request without that token gets a 419. On plain HTTP, put <meta name="csrf-token" content="{{ csrf_token() }}"> in the page, then send its value in the X-CSRF-TOKEN header: headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content }.

This is the Laravel route that makes the ticket. The ticket holds the user name, the expiry time and a nonce (a random value used once), then its signature: an HMAC, a fingerprint of a text computed with a secret key. Only Laravel and the realtime server know that key:

// routes/web.php
Route::post('/api/realtime/ticket', function (Request $request) {
    $payload = $request->user()->username.'.'.(time() + 60).'.'.bin2hex(random_bytes(4));

    return ['ticket' => $payload.'.'.hash_hmac('sha256', $payload, config('services.realtime.secret'))];
})->middleware('auth');

The realtime server checks the ticket with the same secret key:

// realtime server (Node), the same secret in REALTIME_SECRET
import { createHmac, timingSafeEqual } from 'node:crypto'
const used = new Set()

function checkTicket(ticket) {
  const [user, exp, nonce, signature] = String(ticket).split('.')
  const expected = createHmac('sha256', process.env.REALTIME_SECRET).update(`${user}.${exp}.${nonce}`).digest('hex')
  if (!signature || signature.length !== expected.length || !timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) return null
  if (Number(exp) * 1000 < Date.now()) return null // past its 60 seconds
  if (used.has(nonce)) return null                 // already used
  used.add(nonce)
  return user
}

Option 3: Socket.IO's auth payload, checked in middleware

Socket.IO has a place for login data: the auth option. Its content is sent when the client connects to the namespace, and middleware reads it in socket.handshake.auth:

// browser: the auth function runs on every connection attempt, so the ticket is always fresh
const staff = io('http://localhost:3000/staff', {
  auth: (cb) =>
    fetch('/api/realtime/ticket', { method: 'POST', headers: { Accept: 'application/json' } })
      .then((r) => r.json())
      .then(({ ticket }) => cb({ ticket })),
})

// server
io.of('/staff').use((socket, next) => {
  const user = checkTicket(socket.handshake.auth.ticket)
  if (!user) return next(new Error('invalid ticket'))
  socket.data.user = user // used by other handlers, not a role sent by the client
  next()
})

Why not a token in the query string

io(url, { query: { token } }) or new WebSocket('ws://localhost:3000/board?token=...') puts the token in the query string, the part of the URL after the question mark. Tried, the server receives GET /socket.io/?token=eyJhbGciOiJIUzI1NiJ9.secret&EIO=4&transport=websocket&sid=.... A full URL like that is written into Nginx access logs (a record of every request that comes in), proxies and monitoring tools. So anyone who reads the logs can see the token. If it has to go in the URL (a plain WebSocket without Socket.IO), put a 60-second single-use ticket there, not a login token.

Long connections: check again

A WebSocket connection can stay open for hours. A session that was valid at the handshake can expire (Laravel's default is 120 minutes) or be revoked, for example when Eko logs out or leaves the job. Checking once at the start is not enough. In this code, the server cuts each connection off after 2 hours, and cuts off all of Eko's connections through the private room user:eko when he logs out:

staff.on('connection', (socket) => {
  const limit = setTimeout(() => socket.disconnect(true), 2 * 60 * 60 * 1000) // a new ticket every 2 hours
  socket.on('disconnect', () => clearTimeout(limit))
  socket.join(`user:${socket.data.user}`)
})
// when Laravel reports that Eko logged out:
staff.in('user:eko').disconnectSockets(true)

// browser
staff.on('disconnect', (reason) => {
  if (reason === 'io server disconnect') staff.connect() // the auth function fetches a new ticket
})

Tried: cut off by the server, the client gets the reason io server disconnect, socket.active becomes false, and the client does not reconnect on its own. That is why the browser code above calls staff.connect(), which calls the auth function again. So Laravel decides. If the session is still valid, a new ticket comes out. If the user has logged out, Laravel answers 401 (not logged in), not a redirect to the login page, thanks to Accept: application/json.

Every room join is checked

Authentication answers "who", authorisation answers "allowed to do what". Mr. Darto may only follow his own order, order:12. The server compares the order's owner with socket.data.user, which the middleware filled in from the ticket, not with what the client sends:

io.on('connection', (socket) => {
  socket.on('order:follow', async (orderId, ack) => {
    const order = await db.order(orderId)
    if (!order || order.customer !== socket.data.user) return ack({ ok: false, error: 'not your order' })
    socket.join(`order:${orderId}`)
    ack({ ok: true })
  })
})

order:follow 12 from Mr. Darto's phone: { ok: true }. order:follow 13 (Wulan's): { ok: false, error: 'not your order' }, and Mr. Darto never enters that room.

⚠️ Holes that are often left open

TL;DR: The browser cannot add headers to the WebSocket handshake: there is only new WebSocket(url, protocols), and an object { headers } throws a SyntaxError. What the browser sends by itself is the Origin header (the page's site) and cookies, which ignore ports. A session cookie needs an Origin check in allowRequest, because CORS does not apply to WebSockets: another site can open a WebSocket that carries the victim's cookies (Cross-Site WebSocket Hijacking). Another way: a 60-second single-use ticket from POST /api/realtime/ticket, signed with HMAC (a fingerprint computed with a secret key), sent in Socket.IO's auth payload (the first packet, not the URL), then checked in middleware. A token in the query string ends up in logs. Connections stay open, so check again: cut them off when the session expires or at logout, then reconnect with a new ticket. Every room join is checked too: Mr. Darto may only join order:12.

⚡ The browser cannot add headers

Guess first: does it work if you write new WebSocket(url, { headers: { Authorization: 'Bearer abc' } })?

It does not. The second argument is read as subprotocols (names of extra message rules, not headers), so all three browsers throw a SyntaxError.

Meaning: What the browser sends by itself in the handshake is only the Origin header (the page's site address) and cookies. CORS does not apply to WebSockets, so another site can connect with the victim's cookie: check Origin in allowRequest, the Socket.IO server option that checks every connection.

⚡ A ticket in the first packet

Write:

io.of('/staff').use((socket, next) => {
  const user = checkTicket(socket.handshake.auth.ticket)
  if (!user) return next(new Error('invalid ticket'))
  socket.data.user = user // used by other handlers, not a role sent by the client
  next()
})

Meaning: This middleware runs before a connection to the /staff namespace is accepted. A ticket is an entry pass from Laravel that is valid for 60 seconds and can be used once. The browser sends it in Socket.IO's auth payload, in the first packet, and checkTicket checks it. This is the "token at the handshake or in the first message" form. A token in the query string (the part of the URL after the question mark) ends up in logs.

⚡ Long connections: check again

Meaning: A WebSocket connection can stay open for hours, and a session that was valid at the handshake can expire or be revoked. Cut the connection off at expiry or logout, then reconnect with a new ticket. Every room join is checked too: Mr. Darto may only join order:12, his order.

What you will learn