1.aws cloudfront后台创建公有密钥并将密钥添加至密钥组
2. 配置aws cloudfront 分配域名的行为
编辑行为,开启限制查看器访问,选择可信密钥组,添加之前创建的密钥组
3.php实现代码
use Aws\CloudFront\CloudFrontClient;
use Aws\Exception\AwsException;
/**
* aws cloudfront 防盗链
* @param [type] $resourceKey [资源路径]
* @param [type] $expire [过期时间]
* @return [type] [string]
*/
public static function getPrivateSignedUrl($resourceKey, $expire = 300) {
$privateKey = './cert/cloudfront/private_key.pem'; //cloudfront生成密钥的private_key.pem,生成方法见上面文档
$keyPairId = '密钥id';
$region = "region";
$version = "version";
$cloudFrontClient = new CloudFrontClient([
'profile' => 'default',
'version' => $version,
'region' => $region
]);
$expires = time() + intval($expire); // default 5 minutes (5 * 60 seconds) from now.
//$remoteip = get_ip();
//"IpAddress": {"AWS:SourceIp": "{$remoteip}/32"} //可添加至下面的Condition里限制ip
$customPolicy = <<<POLICY
{
"Statement": [
{
"Resource": "{$resourceKey}",
"Condition": {
"DateLessThan": {"AWS:EpochTime": {$expires}}
}
}
]
}
POLICY;
return self::signPrivateDistributionPolicy($cloudFrontClient, $resourceKey, $customPolicy, $privateKey, $keyPairId);
}
/*
* - $cloudFrontClient: An initialized CloudFront client.
* - $resourceKey: A CloudFront URL to the restricted content.
* - $customPolicy: A policy statement that controls the access that a signed
* URL grants to a user.
* - $privateKey: The path to the CloudFront private key file, in .pem format.
* - $keyPairId: The corresponding CloudFront key pair ID.
*
* Returns: The signed URL
*
*/
public static function signPrivateDistributionPolicy($cloudFrontClient, $resourceKey, $customPolicy, $privateKey, $keyPairId)
{
try {
$result = $cloudFrontClient->getSignedUrl([
'url' => $resourceKey,
'policy' => $customPolicy,
'private_key' => $privateKey,
'key_pair_id' => $keyPairId
]);
return $result;
} catch (AwsException $e) {
echo 'get cloudfront signed url error: ' . $e->getAwsErrorMessage();
return '';
}
}