Course contentsShow
← Node.js
Lesson 595 of 1,9806. Networking and HTTP FundamentalsFree lesson

Handling WebSocket Handshake Auth

Verify tokens within the WebSocket upgrade HTTP request before allowing the connection to switch protocols.

In this lesson, you will learn how to secure your WebSocket connections by validating authentication tokens during the initial HTTP upgrade request.

The "Gatekeeper" Pattern

When a client initiates a WebSocket connection, they send a standard HTTP GET request with an Upgrade: websocket header. This handshake is our one and only chance to verify the user's identity before the server commits to a persistent, full-duplex TCP connection.

If you wait until the connection is already established to check credentials, you risk wasting server resources on unauthenticated or malicious clients. Instead, treat the HTTP upgrade as a "gatekeeper" event.

Implementing the Handshake Check

In Node.js, we intercept the upgrade event on the HTTP server. Before we allow the ws library to complete the handshake, we extract the credentials (usually from a query string or an Authorization header) and validate them.

server.on('upgrade', (request, socket, head) => {
  // Extract token from query string: /chat?token=xyz
  const token = new URL(request.url, 'http://base').searchParams.get('token');

  if (!isValid(token)) {
    // Reject the connection before the protocol switch
    socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
    socket.destroy();
    return;
  }

  // If valid, proceed with the handshake
  wss.handleUpgrade(request, socket, head, (ws) => {
    wss.emit('connection', ws, request);
  });
});

Why this matters

By performing this check during the upgrade phase, we ensure that:

  1. Resource Efficiency: We never enter the expensive process of maintaining a persistent socket for unauthorized users.
  2. Security: We prevent unauthorized clients from even reaching the application layer of your WebSocket handlers.
  3. Control: We can enforce specific policies (like limiting concurrent connections per user) before the protocol switch even completes.

Think of the HTTP upgrade as an ID checkpoint at the entrance of a building. Once the person is inside the building (the WebSocket connection), they are free to roam, so you must verify their credentials before you open the door.

Key Takeaway: Always validate authentication tokens during the HTTP upgrade handshake to reject unauthorized traffic before a persistent WebSocket connection is established.