Skip to content

Instantly share code, notes, and snippets.

@wouterdewinter
Forked from anonymous/sign.php
Last active October 2, 2019 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wouterdewinter/8d1c5df157fb676e104dcc32a949462c to your computer and use it in GitHub Desktop.
Save wouterdewinter/8d1c5df157fb676e104dcc32a949462c to your computer and use it in GitHub Desktop.
Tutorial: Securing private content on AWS Cloudfront
<?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