Skip to content

Instantly share code, notes, and snippets.

@miljan-aleksic
Last active December 5, 2023 01:17
Show Gist options
  • Save miljan-aleksic/7699e24f477be7994a26b1e6a150d84e to your computer and use it in GitHub Desktop.
Save miljan-aleksic/7699e24f477be7994a26b1e6a150d84e to your computer and use it in GitHub Desktop.
Cloudflare Streams - Signed URL php example
<?php
class Stream
{
/**
* Signs a url token for the stream reproduction
*
* @param string $uid The stream uid.
* @param array $key The key id and pem used for the signing.
* @param string $exp Expiration; a unix epoch timestamp after which the token will not be accepted.
* @param string $nbf notBefore; a unix epoch timestamp before which the token will not be accepted.
*
* https://dev.to/robdwaller/how-to-create-a-json-web-token-using-php-3gml
* https://developers.cloudflare.com/stream/viewing-videos/securing-your-stream#creating-a-signing-key
*
*/
public static function signToken(string $uid, array $key, string $exp = null, string $nbf = null)
{
$privateKey = base64_decode($key['pem']);
$header = ['alg' => 'RS256', 'kid' => $key['id']];
$payload = ['sub' => $uid, 'kid' => $key['id']];
if ($exp) {
$payload['exp'] = $exp;
}
if ($nbf) {
$payload['nbf'] = $nbf;
}
$encodedHeader = self::base64Url(json_encode($header));
$encodedPayload = self::base64Url(json_encode($payload));
openssl_sign("$encodedHeader.$encodedPayload", $signature, $privateKey, 'RSA-SHA256');
$encodedSignature = self::base64Url($signature);
return "$encodedHeader.$encodedPayload.$encodedSignature";
}
protected static function base64Url(string $data)
{
return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($data));
}
}
@MuriloMazzeu
Copy link

Good dude, this code help me a lot, thanks

@Matt-B50
Copy link

Excellent dude, this helped me a lot too!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment