0
0
Expressframework~5 mins

Authentication in WebSocket connections in Express

Choose your learning style9 modes available
Introduction

Authentication in WebSocket connections helps verify who is connecting. It keeps your app safe by allowing only trusted users to communicate.

When you want to allow only logged-in users to send and receive messages.
When you need to protect real-time data like chat messages or notifications.
When you want to track user activity securely over a WebSocket.
When your app requires user identity to customize the data sent over WebSocket.
Syntax
Express
const WebSocket = require('ws');
const wss = new WebSocket.Server({ noServer: true });

server.on('upgrade', (request, socket, head) => {
  // Extract token from request headers or URL
  const token = extractToken(request);

  if (isValidToken(token)) {
    wss.handleUpgrade(request, socket, head, (ws) => {
      wss.emit('connection', ws, request);
    });
  } else {
    socket.destroy();
  }
});

Authentication usually happens during the HTTP upgrade request before WebSocket connection is established.

You can extract tokens from headers, cookies, or URL query parameters.

Examples
Using the sec-websocket-protocol header to pass a token for authentication.
Express
const token = request.headers['sec-websocket-protocol'];
if (token === 'my-secret-token') {
  // Accept connection
}
Extracting token from URL query parameters during upgrade request.
Express
const url = new URL(request.url, 'http://localhost');
const token = url.searchParams.get('token');
if (token === 'valid-token') {
  // Accept connection
}
Sample Program

This example shows a simple WebSocket server using Express's HTTP server. It checks a token from the URL query during the upgrade request. If the token is correct, it accepts the connection and sends a welcome message. Otherwise, it rejects the connection.

Express
const http = require('http');
const express = require('express');
const WebSocket = require('ws');

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ noServer: true });

function isValidToken(token) {
  return token === 'secret123';
}

server.on('upgrade', (request, socket, head) => {
  const url = new URL(request.url, 'http://localhost');
  const token = url.searchParams.get('token');

  if (!isValidToken(token)) {
    socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
    socket.destroy();
    return;
  }

  wss.handleUpgrade(request, socket, head, (ws) => {
    wss.emit('connection', ws, request);
  });
});

wss.on('connection', (ws) => {
  ws.send('Welcome! You are authenticated.');
  ws.on('message', (message) => {
    ws.send(`You said: ${message}`);
  });
});

server.listen(8080, () => {
  console.log('Server listening on http://localhost:8080');
});
OutputSuccess
Important Notes

Always validate tokens securely, for example by checking against a database or using JWT verification.

Do not trust tokens sent from the client without verification.

Use secure WebSocket (wss://) in production to protect data in transit.

Summary

Authentication happens during the HTTP upgrade request before WebSocket connection starts.

Tokens can be sent via headers or URL query parameters for verification.

Reject unauthorized connections by closing the socket early.