पाठ 24 / 32
Authenticating WebSocket Connections
यह पाठ अभी हिंदी में अनुवादित नहीं है, इसलिए अंग्रेज़ी में दिखाया जा रहा है।
Authenticate WebSocket upgrades with cookies or short-lived tickets, and re-check authorisation on every action.
लेखक: Rahul Agarwal · 15 साल से वेब डेवलपर
Authenticate at the upgrade, authorise every message
The browser WebSocket constructor cannot set an Authorization header, so the usual bearer-token approach does not apply directly. There are three common options. Cookies: the upgrade request carries the site's cookies automatically, so an existing session cookie works, but then you must check Origin (next topic). A short-lived ticket: the client first calls an authenticated HTTP endpoint that returns a random, single-use ticket valid for perhaps 30 seconds, then connects with ?ticket=...; the server validates and deletes it during the upgrade. Long-lived tokens in URLs are risky because URLs end up in logs. A first message: connect, then send { "type": "auth", "token": ... } and close the socket if it does not arrive quickly. Whatever you choose, reject before upgrading when you can, and remember that a connection may outlive the user's session: re-check permissions when joining rooms and close with 1008 when a token expires or access is revoked.
Gates on the way in
A request passes several checks before it becomes a trusted socket: the upgrade request, the Origin check, the credential check, and then validation of every message that follows.
Checking a ticket and Origin before upgrading
With noServer: true the HTTP server's upgrade event decides. Bad requests get a 401 written to the raw socket and never become WebSockets; good tickets are deleted after use so a leaked URL cannot be replayed. In a test, the first connection with ticket t-9f2c was welcomed and a second attempt with the same ticket was rejected.
import http from 'node:http';
import { WebSocketServer } from 'ws';
const tickets = new Map([['t-9f2c', { userId: 'u42' }]]); // short-lived, single-use
const ALLOWED_ORIGINS = new Set(['https://app.example.in']);
const server = http.createServer();
const wss = new WebSocketServer({ noServer: true, maxPayload: 64 * 1024 });
server.on('upgrade', (req, socket, head) => {
const url = new URL(req.url, 'http://localhost');
const ticket = url.searchParams.get('ticket');
const user = tickets.get(ticket);
const originOk = ALLOWED_ORIGINS.has(req.headers.origin);
if (!user || !originOk) {
socket.write('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n');
socket.destroy();
return;
}
tickets.delete(ticket); // single use: a leaked URL cannot be replayed
wss.handleUpgrade(req, socket, head, (ws) => {
ws.user = user;
wss.emit('connection', ws, req);
});
});
wss.on('connection', (ws) => ws.send(`welcome ${ws.user.userId}`));
server.listen(8082);Expire long-lived sessions on the socket too
A socket opened at 9 a.m. with a one-hour token is still open at 5 p.m. unless you act. Track the token's expiry per connection and close with 1008 (or ask the client to re-authenticate with a fresh token message) when it passes.
त्वरित जाँच: Why do many apps use a short-lived, single-use ticket in the WebSocket URL instead of the user's long-lived access token?
- Browsers block query strings on wss:// URLs
- URLs are often logged, so a leaked ticket must expire quickly and be useless after first use
- Tickets make frames smaller
- The handshake rejects tokens longer than 64 bytes
Answer
URLs are often logged, so a leaked ticket must expire quickly and be useless after first use — Query strings show up in proxy and server logs. A ticket that is single-use and expires in seconds limits the damage if it leaks.