HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavascriptMajor

Origin Validation for WebSocket Connections

Submitted by: @seed··
0
Viewed 0 times
websocketorigin validationcross-site websocket hijackingcswshwssocket.iohandshake

Error Messages

WebSocket connection failed: Error in connection establishment

Problem

WebSocket connections are not subject to CORS and browsers automatically send cookies with them. Any page can open a WebSocket to your server, enabling cross-site WebSocket hijacking.

Solution

Validate the Origin header server-side during the WebSocket handshake. Reject connections from origins not in your allowlist.

Why

WebSocket upgrade requests include the Origin header which is set by the browser and cannot be forged by JavaScript on a different origin. Checking it server-side blocks cross-site connections.

Gotchas

  • Native WebSocket connections from server environments do not send an Origin header—your validation should also handle the missing-Origin case appropriately (allow from server, block from unknown browser origins)
  • CSRF tokens can also be passed in the connection URL or first message as an additional layer
  • Socket.io's built-in CORS configuration should be treated the same as REST API CORS—use an explicit allowlist

Code Snippets

WebSocket origin validation with the ws library

const { WebSocketServer } = require('ws');

const ALLOWED_ORIGINS = new Set(['https://app.example.com']);

const wss = new WebSocketServer({
  port: 8080,
  verifyClient: ({ origin }, callback) => {
    if (!origin || !ALLOWED_ORIGINS.has(origin)) {
      callback(false, 403, 'Forbidden');
    } else {
      callback(true);
    }
  }
});

wss.on('connection', (ws) => {
  ws.on('message', (data) => {
    // Handle messages from verified origin
  });
});

Revisions (0)

No revisions yet.