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
})
allowRequestchecks theOriginheader of every connection. Tried: the other site's page getsconnect_error(websocket error) right away, and the laundry page still connects.- Laravel 13's session cookie is
SameSite=LaxandHttpOnly(JavaScript cannot read it) by default.SameSite=Laxholds other sites back, but not another port or subdomain of the same site. A subdomain is an extra name in front of the site's name. So check the Origin anyway.
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
}
timingSafeEqualcompares signatures in the same time however many characters match, so the time taken does not leak the right signature.- The ticket
rini.1791686520.9f2c41d0.<signature>is made at 09:41:00 and is valid until 09:42:00 (1791686520is 09:42:00, in seconds since 1 January 1970). Tried:hash_hmacin PHP andcreateHmacin Node give the same signature,2ea1c4d8.... - Used at 09:41:01: in as
rini. Used again: refused (already used). A similar new ticket first used at 09:42:05: refused (expired). - With several Node processes, keep the nonces in Redis, because
usedlives in one process's memory:SET ticket:9f2c41d0 1 NX EX 60(NX: only if not there yet,EX 60: deleted after 60 seconds).
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()
})
authis sent in the first packet,40/staff,{"ticket":"..."}, not in the URL. This is the "token at the handshake or in the first message" form.- Tried: a connection refused by the middleware fires
connect_errorwith the messageinvalid ticket.socket.activebecomesfalse: the client does not try to reconnect on its own.
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
- Relying on Socket.IO's
corsto keep other sites out. That option only covers polling. CheckOrigininallowRequest. - A login token in the query string. It ends up in logs. Use
auth, or a 60-second single-use ticket. - Checking only when connecting. A connection that lasts hours outlives expiry and logout. Cut it off and ask for a new ticket.
- Trusting a room name or a role sent by the client. Check every
order:followagainst the order's owner in the database.
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.