Forked from anunay/self-signed-cloudfront-urls-using-private-key.php
Created
March 25, 2024 03:57
-
-
Save trieuconcrete/72d12034229dd1275411d7e1041d3b76 to your computer and use it in GitHub Desktop.
PHP - Signed CloudFront urls with private key
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 | |
/** | |
* Sign a private asset url on cloudfront | |
* | |
* @param $resource full url of the resources | |
* @param $timeout timeout in seconds | |
* @return string signed url | |
* @throws Exception | |
*/ | |
function getSignedURL($resource, $timeout) | |
{ | |
// This is the id of the Cloudfront key pair you generated | |
$keyPairId = "[key id obtained from step 1]"; | |
$expires = time() + $timeout; // Timeout in seconds | |
$json = '{"Statement":[{"Resource":"'.$resource.'","Condition":{"DateLessThan":{"AWS:EpochTime":'.$expires.'}}}]}'; | |
// Read Cloudfront Private Key Pair, do not place it in the webroot! | |
$fp = fopen("/app/data/private_key.pem", "r"); | |
$priv_key = fread($fp,8192); | |
fclose($fp); | |
// Create the private key | |
$key = openssl_get_privatekey($priv_key); | |
if (!$key) { | |
throw new Exception('Loading private key failed'); | |
} | |
// Sign the policy with the private key | |
if (!openssl_sign($json, $signed_policy, $key, OPENSSL_ALGO_SHA1)) { | |
throw new Exception('Signing policy failed, '.openssl_error_string()); | |
} | |
// Create url safe signed policy | |
$base64_signed_policy = base64_encode($signed_policy); | |
$signature = str_replace(array('+','=','/'), array('-','_','~'), $base64_signed_policy); | |
// Construct the URL | |
$url = $resource . (strpos($resource, '?') === false ? '?' : '&') . 'Expires='.$expires.'&Signature=' . $signature . '&Key-Pair-Id=' . $keyPairId; | |
return $url; | |
} | |
// Example usage | |
echo '<img src="' . getSignedURL("http://[your-distribution].cloudfront.net/your-asset.png", 60) . '" />'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment