How to Secure WebSocket Connections: Origin Checks and Signature Authentication
This article explains why WebSocket security matters, outlines authentication and authorization gaps, describes the Cross‑Site WebSocket Hijacking (CSWSH) attack, and provides practical PHP code for origin validation and signature‑based authentication to protect high‑concurrency WebSocket services.
Background
WebSocket is increasingly used in live streaming, remote education, instant messaging and enterprise notification systems, where services must support millions of concurrent connections with high availability.
Security Risks
WebSocket does not define built‑in authentication or authorization. The handshake can reuse any HTTP authentication method, so the same vulnerabilities that affect traditional web apps (e.g., CVE‑2015‑0201, CVE‑2015‑1482) also apply. Because the protocol relies on an Origin header for cross‑origin protection, missing or unchecked origins enable Cross‑Site WebSocket Hijacking (CSWSH), where a malicious page forces an authenticated user’s browser to open a WebSocket connection and reuse cookies.
Mitigation Strategy
A robust defense combines strict Origin validation with a time‑limited signature token, similar to CSRF protection.
1. Origin Header Validation
Register an onConnect callback in the Gateway‑Worker configuration to reject connections whose HTTP_ORIGIN header is absent or does not match the trusted domain.
config\plugin\webman\gateway-worker\process.php return [
'gateway' => [
'handler' => Gateway::class,
'listen' => 'websocket://0.0.0.0:8783',
'count' => cpu_count(),
'reloadable' => false,
'constructor' => [
'config' => [
'lanIp' => '127.0.0.1',
'startPort' => 2300,
'pingInterval' => 25,
'pingData' => '{"type":"ping"}',
'registerAddress' => '127.0.0.1:12306',
'onConnect' => function ($connection) {
$connection->onWebSocketConnect = function ($connection, $header) {
// ---- Origin check ----
if (!isset($_SERVER['HTTP_ORIGIN'])) {
echo "[x] HTTP_ORIGIN not defined
";
return $connection->close();
}
if ($_SERVER['HTTP_ORIGIN'] !== 'https://tinywan.com') {
echo "[x] HTTP_ORIGIN not allowed
";
return $connection->close();
}
echo "[✓] ORIGIN validated
";
// ---- Signature check ----
if (!isset($_GET['sign']) || !isset($_GET['ts'])) {
echo "[x] Missing signature parameters
";
return $connection->close();
}
$secret = 'Tinywan2024';
$serverSign = sha1($_GET['ts'] . '|' . $secret);
if ($_GET['sign'] !== $serverSign) {
echo "[x] Invalid signature
";
return $connection->close();
}
echo "[✓] Signature validated
";
return true;
};
},
],
],
],
];2. Signature‑Based Authentication
Generate a short‑lived signature on the server and require the client to attach ts (timestamp) and sign as query parameters.
/**
* Generate WebSocket connection signature
* @return array
*/
function get_wss_sign(): array
{
$ts = time() + 360; // valid for 6 minutes
$secret = 'Tinywan2024';
return [
'sign' => sha1($ts . '|' . $secret),
'ts' => $ts,
];
}Client‑side JavaScript builds the URL with the returned parameters and opens the connection:
var ws = new WebSocket("ws://127.0.0.1:8783/?ts=1701697325&sign=3c99ce96521602cf54df53f65cc07b977e33a27c");
ws.onopen = function () {
console.log("Connection open ...");
var payload = {
mode: 1,
from_username: "Tinywan",
to_user_id: "10000",
content: "Hi, 开源技术小栈"
};
ws.send(JSON.stringify(payload));
};
ws.onmessage = function (evt) {
console.log("Received Message: " + evt.data);
};
ws.onclose = function () {
console.log("Connection closed.");
};Testing confirms that connections with an illegal HTTP_ORIGIN are rejected, while those with a matching origin and a correct signature are accepted.
Reference Implementation
The complete source code for this example is available at:
https://github.com/Tinywan/webman-admin
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
