Azure Web PubSub negotiate via PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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}", | |
]; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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