Skip to content

Instantly share code, notes, and snippets.

@velotiotech
Created February 23, 2022 10:04
Show Gist options
  • Save velotiotech/e5fe8d0baf3dbef5b92a7bca126b6a6f to your computer and use it in GitHub Desktop.
Save velotiotech/e5fe8d0baf3dbef5b92a7bca126b6a6f to your computer and use it in GitHub Desktop.
import functools
import rsa
from botocore.signers import CloudFrontSigner
CLOUDFRONT_RESOURCE = # IN format "{protocol}://{domain}/{resource}" for e.g. "https://d1g71lhh75winl.cloudfront.net/*"
CLOUDFRONT_PUBLIC_KEY_ID = # The ID for a CloudFront public key
CLOUDFRONT_PRIVATE_KEY = # contents of the private_key.pem file associated to public key e.g. open('private_key.pem','rb').read()
EXPIRES_AT = # Enter datetime for expiry of cookies e.g.: datetime.datetime.now() + datetime.timedelta(hours=1)
# load the private key
key = rsa.PrivateKey.load_pkcs1(CLOUDFRONT_PRIVATE_KEY)
# create a signer function that can sign message with the private key
rsa_signer = functools.partial(rsa.sign, priv_key=key, hash_method="SHA-1")
# Create a CloudFrontSigner boto3 object
signer = CloudFrontSigner(CLOUDFRONT_PUBLIC_KEY_ID, rsa_signer)
# build the CloudFront Policy
policy = signer.build_policy(CLOUDFRONT_RESOURCE, EXPIRES_AT).encode("utf8")
CLOUDFRONT_POLICY = signer._url_b64encode(policy).decode("utf8")
# create CloudFront Signature
signature = rsa_signer(policy)
CLOUDFRONT_SIGNATURE = signer._url_b64encode(signature).decode("utf8")
# you can set this cookies on response
COOKIES = {
"CloudFront-Policy": CLOUDFRONT_POLICY,
"CloudFront-Signature": CLOUDFRONT_SIGNATURE,
"CloudFront-Key-Pair-Id": CLOUDFRONT_PUBLIC_KEY_ID,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment