Skip to content

Instantly share code, notes, and snippets.

@kaz29
Created June 13, 2021 21:43
Show Gist options
  • Save kaz29/61a70f1d19ffdf26da30522d31638759 to your computer and use it in GitHub Desktop.
Save kaz29/61a70f1d19ffdf26da30522d31638759 to your computer and use it in GitHub Desktop.
Azure Web PubSub negotiate via PHP
<?php
declare(strict_types=1);
class PubSubToken {
protected $endpoint;
protected $wssEndpoint;
protected $accesskey;
protected $version;
protected $alg = 'HS256';
public function __construct($connectionString)
{
$params = explode(';', $connectionString);
foreach ($params as $param) {
list($k, $v) = explode('=', $param, 2);
$this->{strtolower($k)} = $v;
}
$this->wssEndpoint = preg_replace('/(http)(s?:\/\/)/i', 'ws$2', $this->endpoint);
if ($this->endpoint === null || $this->accesskey === null || $this->version === null || $this->wssEndpoint === null) {
throw new \Exception('Parameter error');
}
}
public function getAuthenticationToken(string $hub, string $userId = null, int $ttl = 3600): array
{
$now = time();
$payload = [
'iat' => $now,
'exp' => $now + $ttl,
'aud' => "{$this->endpoint}/client/hubs/{$hub}",
];
if ($userId !== null) {
$payload['sub'] = $userId;
}
$jwt = new \JOSE_JWT($payload);
$jwt->header['alg'] = $this->alg;
$jwt->header['typ'] = 'JWT';
$jwt->sign($this->accesskey, $this->alg);
$jws = new \JOSE_JWS($jwt);
$jws = $jws->sign($this->accesskey, $this->alg);
$token = $jws->toString();
return [
'baseUrl' => "{$this->wssEndpoint}/client/hubs/{$hub}",
'token' => $token,
'url' => "{$this->wssEndpoint}/client/hubs/{$hub}?access_token={$token}",
];
}
}
<?php
$connectionString = 'Your Azure Web PubSub connection string';
$pubsub = new PubSubToken($connectionString);
$token = $pubsub->getAuthenticationToken('test');
var_dump($token);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment