Forked from chilledornaments/Python3-CloudFront-SignedURL
Created
September 25, 2025 08:05
-
-
Save dogrocker/a7c65206555bb9885f69f83f0326942f to your computer and use it in GitHub Desktop.
Walkthrough of creating a CloudFront Signed URL with Python + Boto3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python36 | |
import boto3, rsa, datetime | |
from botocore.signers import CloudFrontSigner | |
from datetime import timedelta | |
""" | |
First things first, sign into your AWS Root account. Per Amazon's documentation: | |
IAM users can't create CloudFront key pairs. You must log in using root credentials to create key pairs. | |
Link: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-trusted-signers.html | |
Go to My Security Credentials (top right under the account name drop-down) | |
Expand "CloudFront key pairs" | |
Click "Create New Key Pair" | |
Download the private key. | |
Save the private key and `chmod` it + the folder as if it were an SSH key. | |
Take note of the "Access Key ID", that's what you'll use for the "KEY_PAIR_ID" variable. | |
If you haven't set up S3 + OAI + CloudFront, do that. | |
Grab the CloudFront distribution name. Or if you've set up your own domain, use that. Whichever one you choose, it will be the value for the | |
PRIVATE_CF_DISTRO variable. | |
Set the ASSET_NAME to whatever you have in S3 that you want to create a signed URL for. Specifying an S3 filepath works too. | |
You can change the expiration to whatever you'd like. | |
You should be good to go. | |
""" | |
PRIVATE_KEY_FILE = "/path/to/key/that/you/created/and/downloaded/from/aws/console/privatekey.pem" | |
KEY_PAIR_ID = "XXXXXXXXXXXXXXXXXXXX" | |
PRIVATE_CF_DISTRO = "xxxxxxx.cloudfront.net" | |
ASSET_NAME = "test.jpg" | |
def rsa_signer(message): | |
private_key = open(PRIVATE_KEY_FILE, 'r').read() | |
return rsa.sign( | |
message, | |
rsa.PrivateKey.load_pkcs1(private_key.encode('utf8')), | |
'SHA-1') | |
cf_signer = CloudFrontSigner(KEY_PAIR_ID, rsa_signer) | |
url = "https://{}/{}".format(PRIVATE_CF_DISTRO, ASSET_NAME) | |
expires = datetime.datetime.now() + timedelta(days=735) | |
signed_url = cf_signer.generate_presigned_url(url, date_less_than=expires) | |
print(signed_url) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment