php aws cloudfront基于时间或ip的签名url实现防盗链

1.aws cloudfront后台创建公有密钥并将密钥添加至密钥组

文档: https://docs.aws.amazon.com/zh_cn/AmazonCloudFront/latest/DeveloperGuide/private-content-trusted-signers.html

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 '';
        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值