Secure WebSocket Connections with JWT Using GatewayWorker and PHP
This guide explains how to implement JWT‑based authentication for WebSocket connections in PHP using the GatewayWorker framework, covering token generation, server‑side validation, client‑side usage, and practical code examples.
Overview
WebSocket provides real‑time communication but does not include authentication. JSON Web Tokens (JWT) can be used to authenticate clients by passing the token as a query parameter in the WebSocket URL.
Authentication
During the handshake the server extracts the Authorization query parameter, validates the JWT, and only accepts the connection if the token is valid.
Server‑side – GatewayWorker
GatewayWorker is a distributed TCP long‑connection framework built on Workerman, suitable for push services, instant messaging, games, IoT, etc.
Installation documentation:
https://www.workerman.net/doc/gateway-workerInstall JWT plugin
composer require tinywan/php-jwtGenerate a JWT (PHP)
<?php
declare(strict_types=1);
require 'vendor/autoload.php';
$secretKey = 'Tinywan2050040000011';
$jwt = new \Tinywan\Jwt($secretKey);
$payload = [
'user_id' => 20501000001,
'username'=> 'Tinywan',
'exp' => time() + 3600, // 1 hour expiration
];
$token = $jwt->createToken($payload);
var_dump($token);Sample token:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoyMDUwMTAwMDAwMSwidXNlcm5hbWUiOiJUaW55d2FuIiwiZXhwIjoxNzQ5OTk5NTU1fQ.om7PERuIAzEfPoEui1wJd40M4QJ-CE5gMisiG7Gc0NYServer‑side authentication callback
// Set up onWebSocketConnect callback
$gateway->onConnect = function ($connection) {
$connection->onWebSocketConnect = function ($connection, $http_header) {
$secretKey = 'Tinywan2050040000011';
$jwt = new \Tinywan\Jwt($secretKey);
$token = $_GET['Authorization'];
if ($jwt->validateToken($token)) {
echo "JWT is valid.
";
$decoded = $jwt->decodeToken($token);
echo "Decoded Payload: " . json_encode($decoded, JSON_PRETTY_PRINT) . "
";
} else {
echo "JWT is invalid.
";
$connection->close();
return;
}
return true;
};
};Client side
The token is appended to the WebSocket URL because the browser API cannot set custom HTTP headers during the handshake.
Connection example
ws://127.0.0.1:8782/?Authorization=Bearer eyJ0eXAi...JavaScript debug example
var ws = new WebSocket('ws://127.0.0.1:8782/?Authorization=' + token);
ws.onmessage = function (event) {
console.log('Message received: ' + event.data);
};Header‑based alternative (if server supports)
headers: {
Authorization: "Bearer " + getToken(),
}References
PHP如何创建和管理JWT令牌: https://mp.weixin.qq.com/s?__biz=MzUzMDMxNTQ4Nw==∣=2247492104&idx=1&sn=b3b17c7552687cdfe7cbdb3d009d22c6&scene=21#wechat_redirect
PHP分布式TCP长连接框架 GatewayWorker: https://mp.weixin.qq.com/s?__biz=MzUzMDMxNTQ4Nw==∣=2247501072&idx=1&sn=fe86e24f2285e729482ee0c2728abb2a&scene=21#wechat_redirect
WebSocket教程:JWT身份验证参数方式有哪些?: https://mp.weixin.qq.com/s?__biz=MzUzMDMxNTQ4Nw==∣=2247493443&idx=1&sn=44deaac9d3b3cc6376ed4e5639db9eb1&scene=21#wechat_redirect
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.
