Last active
December 5, 2023 01:17
-
-
Save miljan-aleksic/7699e24f477be7994a26b1e6a150d84e to your computer and use it in GitHub Desktop.
Cloudflare Streams - Signed URL php example
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 | |
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)); | |
} | |
} |
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
Good dude, this code help me a lot, thanks