CloudFront签名URL访问被拒绝

时间:2017-08-08 14:53:56

标签: php amazon-cloudfront

我正在尝试在CloudFront上为我的视频添加签名网址,但是当我打开我的网址时,每当我在此处生成网址代码时,它会向我显示“拒绝访问”错误

<Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<RequestId>081DED49D4E126A6</RequestId>
<HostId>Lx+3mwxdCGo1vWAGM5RzPHDKrwEkvQwi8XiH2hBgj51XWsxu4gqY3Zr+w1x4ZoZQAYWEHV9u1wA=</HostId>
</Error>

这是我的代码,我不知道我做错了什么

<?php
$urlShow = getSignedURL("http://d22bw8b4o37yyl.cloudfront.net/test/love1.mp4", 500);
function getSignedURL($resource, $timeout)
{
    //This comes from key pair you generated for cloudfront
    $keyPairId = "APKAIJP3H7LLN44FL2OQ";

    $expires = time() + $timeout; //Time out in seconds
    $json = '{"Statement":[{"Resource":"'.$resource.'","Condition":{"DateLessThan":{"AWS:EpochTime":'.$expires.'}}}]}';     

    //Read Cloudfront Private Key Pair
    $fp=fopen("pk-APKAIJP3H7LLN44FL2OQ.pem","r"); 
    $priv_key=fread($fp,8192); 
    fclose($fp); 

    //Create the private key
    $key = openssl_get_privatekey($priv_key);
    if(!$key)
    {
        echo "<p>Failed to load private key!</p>";
        return;
    }

    //Sign the policy with the private key
    if(!openssl_sign($json, $signed_policy, $key, OPENSSL_ALGO_SHA1))
    {
        echo '<p>Failed to sign policy: '.openssl_error_string().'</p>';
        return;
    }

    //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.'?Expires='.$expires.'&Signature='.$signature.'&Key-Pair-Id='.$keyPairId;

    return $url;
}

echo $urlShow;
?>

1 个答案:

答案 0 :(得分:0)

你得到的是因为你在代码中使用的到期时间不合适。要解决此问题,首先我们需要更新 Bucket 政策并使用正确的密钥对ID 私钥然后在第二行代码使用正确的Unix时间戳,如time() + 600而不是500 PHP, time - Manual

以下是解决问题的完整代码

<?php
$urlShow = getSignedURL("http://d22bw8b4o37yyl.cloudfront.net/test/love1.mp4", time() + 600);
function getSignedURL($resource, $timeout) {
//This comes from key pair you generated for cloudfront
$keyPairId = "APKAIJP3H7LLN44FL2OQ";

$expires = time() + $timeout; //Time out in seconds
$json = '{"Statement":[{"Resource":"'.$resource.'","Condition":{"DateLessThan":{"AWS:EpochTime":'.$expires.'}}}]}'; 

//Read Cloudfront Private Key Pair
$fp=fopen("pk-APKAIJP3H7LLN44FL2OQ.pem","r"); 
$priv_key=fread($fp,8192); 
fclose($fp); 

//Create the private key
$key = openssl_get_privatekey($priv_key);
if(!$key) {
echo "<p>Failed to load private key!</p>";
return;
}

//Sign the policy with the private key
if(!openssl_sign($json, $signed_policy, $key, OPENSSL_ALGO_SHA1)) {
echo '<p>Failed to sign policy: '.openssl_error_string().'</p>';
return;
}

//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.'?Expires='.$expires.'&Signature='.$signature.'&Key-Pair-Id='.$keyPairId;
return $url;
}

echo $urlShow;
?>