Skip to content

Conversation

@thekid
Copy link
Member

@thekid thekid commented Jul 5, 2025

Motivation

Note: All browsers send an Origin header. You can use this header for security (checking for same origin, automatically allowing or denying, etc.) and send a 403 Forbidden if you don't like what you see.

Source: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers

Usage

use web\handler\WebSocket;

// Uses same-origin policy by default
new WebSocket($handler);

// Also allow browsers to connect from example.com and subdomains using HTTPS
new WebSocket($handler, ['https://example.com', 'https://*.example.com']);

// Allow connecting from any host, e.g. for a websocket API
new WebSocket($handler, ['*']);

⚠️ However, be warned that non-browser agents can set the Origin header to any value. While this default measure is effective against Cross Site WebSocket Hijacking (CSWH), think about further measures like authentication.

See also

@thekid
Copy link
Member Author

thekid commented Jul 5, 2025

The more flexible version would have been:

use web\filters\VerifyOrigin;
use web\handler\WebSocket;

new VerifyOrigin(new WebSocket($handler), VerifyOrigin::SAMEORIGIN);

...but I wanted this handler to be more secure by default.

@thekid thekid merged commit 7fb23cc into master Jul 5, 2025
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants