Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 36 ยท Middleware and Authentication

Authentication During the Handshake

Authenticate Socket.IO connections properly. Send tokens with the auth option, verify them in middleware, understand cookies and sessions, handle expiry and reconnects, and avoid query-string secrets.

A WebSocket is open to anyone who can reach the server. Nothing about opening one proves who you are. So authentication is your job, and the best moment to do it is once, at connection time, in middleware, so that no unauthenticated socket ever reaches your event handlers. This lesson shows the standard approach: the client sends credentials in the auth option, middleware verifies them and stores the identity in socket.data.

Sending credentials from the client

The auth option is an object sent in the Socket.IO CONNECT packet (inside the encrypted connection when you use HTTPS/WSS). The server reads it at socket.handshake.auth:

JavaScript
// client
const socket = io('https://api.example.com', {
  auth: { token: localStorage.getItem('token') },
});

// server
io.use((socket, next) => {
  const token = socket.handshake.auth.token;
  // ... verify ...
});

If the token can change (refresh, re-login), pass a function so the freshest value is read on every connection and every reconnection:

JavaScript
const socket = io(url, {
  auth: (cb) => cb({ token: getCurrentToken() }),
});

To change credentials later, update the option and reconnect: socket.auth = { token: newToken }; socket.disconnect().connect();.

Do not put tokens in the query option. Query strings end up in server logs, proxy logs and browser history. auth travels in the packet body instead. Also always use HTTPS/WSS in production, otherwise credentials cross the network in plain text.

Verifying a token: the JWT idea

The most common credential is a JSON Web Token (JWT): three base64url parts, header.payload.signature. The server signs the header and payload with a secret; anyone changing the payload breaks the signature. In a real project use a vetted library such as jsonwebtoken or jose:

JavaScript
import jwt from 'jsonwebtoken';

io.use((socket, next) => {
  try {
    const payload = jwt.verify(socket.handshake.auth.token, process.env.JWT_SECRET);
    socket.data.userId = payload.sub;
    next();
  } catch (err) {
    const error = new Error(err.name === 'TokenExpiredError' ? 'token expired' : 'invalid token');
    error.data = { code: err.name === 'TokenExpiredError' ? 'TOKEN_EXPIRED' : 'TOKEN_INVALID' };
    next(error);
  }
});

To show the mechanism without any package, the runnable example below builds a simplified HS256 token with Node's node:crypto (an educational stand-in, not a substitute for a vetted library) and verifies it in middleware. It accepts a valid token, and rejects a tampered one, an expired one and a missing one.

Node.js Verifying signed tokens in middleware

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice three details in the code. The signature comparison uses timingSafeEqual, which avoids leaking information through response timing. The expiry (exp) is checked, so a stolen token stops working eventually. And the error message sent to the client is generic (authentication failed) with a safe machine-readable code.

Cookies and sessions

If your web app already has cookie-based sessions, the browser sends the cookie automatically with the handshake when the page and the server share a site (or when you use withCredentials: true plus a matching CORS configuration). The server reads it from socket.request.headers.cookie, or runs the session middleware with the wrap helper from the previous lesson, then checks the session for a user.

Cookie auth is convenient and keeps tokens out of JavaScript (HttpOnly). Its main risk is cross-site WebSocket hijacking: another site can open a WebSocket to your server and the browser will attach your cookies. Mitigate it by verifying the Origin header (CORS origin list, or checking socket.handshake.headers.origin yourself), and by using SameSite cookies.

Token auth through the auth option avoids that risk (the attacking page cannot read your token), but you must store the token somewhere the page can read it, which makes XSS protection important.

Expiry, refresh and reconnection

Tokens expire, but a socket can live for hours. Middleware runs only at connection time, so an old connection stays authenticated even after its token expires. Choose a policy:

  1. Accept it for low-risk apps; expiry affects only new connections.
  2. Disconnect at expiry: set a timer for exp and call socket.disconnect(); the client refreshes its token and reconnects.
  3. Re-authenticate over the wire: the client emits auth:refresh with a new token before expiry; the server verifies it and updates socket.data.

Reconnections run your middleware again with whatever auth the client supplies, so with the function form of auth the client automatically presents a fresh token.

The simulation below follows policy 2: the first connection fails with TOKEN_EXPIRED, the client "refreshes" and connects again.

Node.js Refreshing an expired token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Putting the identity to use

After middleware stores socket.data.userId, every handler can trust it, because it came from the verified token and not from event payloads. Never let a client tell you who it is in an event (socket.emit('message', { from: 'admin', ... })). Instead, always use socket.data.userId as the author on the server side.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should a token be sent for a Socket.IO connection?

    auth travels in the connect packet. Query strings leak into logs and history.
  2. 2. Middleware verified a token an hour ago, and the token has now expired. What is true?

    Middleware runs at connection time only; long-lived sockets need an explicit expiry strategy.
  3. 3. How do you let the client present a fresh token on every reconnect?

    A function form is evaluated on every connection attempt, so it can return the latest token.
  4. 4. A client sends { from: 'admin', text: 'hi' } in a message event. Which value should the server use as the author?

    Identity must come from verified authentication, never from client-supplied fields.

Summary

  • Authenticate once at connection time in middleware; keep unauthenticated sockets away from handlers.
  • Send credentials in auth (use a function for refreshable tokens), never in the query string; use HTTPS/WSS.
  • Verify JWTs with a vetted library, check expiry, and store the identity in socket.data.
  • Cookie sessions are convenient but need an origin check against cross-site WebSocket hijacking.
  • Decide how long-lived sockets handle token expiry, and always take identity from socket.data.

Next: Authorization and Rate Limiting