Рабочий пример, мб кому пригодится, т.к. на php очень мало решений нашёл.
Клиент php:
<?
require __DIR__ . '/vendor/autoload.php';
use Ahc\Jwt\JWT;
use ElephantIO\Client;
use ElephantIO\Engine\SocketIO\Version2X;
$secret = 'shecret';
$host = 'http://localhost';
$port = 3000;
$maxAge = 600;
$payload = [
'data' => '123',
];
$jwt = new JWT($secret, 'HS256', $maxAge);
$token = $jwt->encode($payload);
$client = new Client(new Version2X($host .':'. $port));
$client->initialize();
$client->emit('authenticate', ['token' => $token]);
$isAuthenticated = formatResponse($client->read());
if('authenticated' !== $isAuthenticated['event']){
$client->close();
}
$data = [
'data' => 'from client'
];
$token = $jwt->encode($data);
$client->emit('action', ['token' => $token]);
$response = formatResponse($client->read());
if($response['data']){
$response = ($jwt->decode($response['data']->token))['data'];
}
$client->close();
echo '<pre>';
print_r($response);
echo '</pre>';
function formatResponse($response){
$response = json_decode(preg_replace('/^\d*/i', '', $response));
return $response ? [
'event' => $response[0],
'data' => $response[1],
] : false;
}
Сервер nodeJS:
require("@babel/register");
const
socketIO = require('socket.io'),
jwt = require('jsonwebtoken'),
socketioJwt = require('socketio-jwt'),
port = 3000,
server = socketIO.listen(port),
secret = 'shecret',
maxAge = 600;
server
.on(
'connection',
socketioJwt.authorize({
secret: secret,
timeout: 10000,
callback: false
}
))
.on('connection', socket => {
console.log('on connection to server (server)');
})
.on('authenticated', socket => {
console.log('on authenticated to server (server), socket.decoded_token', socket.decoded_token);
socket.on('action', data => {
console.log('on action (server)', data);
if(data && 'token' in data){
let decoded = null;
try {
decoded = jwt.verify(data.token, secret);
} catch (err) {
console.log(err);
}
if(decoded){
console.log(decoded);
const token = jwt.sign(
{
exp: Math.floor(Date.now() / 1000) + maxAge,
data: 'from server'
},
secret);
socket.emit('action', {token: token});
} else {
socket.disconnect(true);
}
}
})
})
;
Пакеты:
// composer.json
"adhocore/jwt": "^0.1.0",
"wisembly/elephant.io": "^3.3"
// package.json
"jsonwebtoken": "^8.5.1",
"socket.io": "^2.3.0",
"socketio-jwt": "^4.5.0"