amazon-web-servicesamazon-cloudfront

Issues generating CloudFront signed URLs; always Access Denied


I’m having issues generating signed URLs with CloudFront. Whatever I try, I just get an “Access Denied” response.

I’ve created a distribution in CloudFront, and a CloudFront key pair ID. I’ve downloaded the private and public keys for that key pair ID.

In a simple PHP script, I’m trying the following:

use Aws\CloudFront\CloudFrontClient;

$cloudfront = new CloudFrontClient([
    'credentials' => [
        'key' => '[redacted]', // Access key ID of IAM user with Administrator policy
        'secret' => '[redacted]', // Secret access key of same IAM user
    ],
    'debug' => true,
    'region' => 'eu-west-1',
    'version' => 'latest',
]);

$expires = strtotime('+6 hours');

$resource = 'https://[redacted].cloudfront.net/mp4/bunny-trailer.mp4';

$url = $cloudfront->getSignedUrl([
    'url' => $resource,
    'policy' => json_encode([
        'Statement' => [
            [
                'Resource' => $resource,
                'Condition' => [
                    'DateLessThan' => [
                        'AWS:EpochTime' => $expires,
                    ],
                ],
            ],
        ],
    ]),
    'expires' => $expires,
    'key_pair_id' => '[redacted]', // Access key ID of CloudFront key pair
    'private_key' => '[redacted]', // Relative path to pk-[redacted].pem file
]);

But when visiting the generated URL, it just always gives me an error in the browser with a code of “AccessDenied”.

What am I doing wrong?


Solution

  • Discovered what the issue was. The objects in my S3 bucket weren’t publicly-accessible, and I hadn’t added an Origin Access Identity, so CloudFront couldn’t pull the objects from my origin (my S3 bucket) to cache them.

    As soon as I added an Origin Access Identity and added it to my S3 bucket’s policy, my objects immediately became accessible through my CloudFront distribution via signed URLs.

    Relevant documentation: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html#private-content-creating-oai