Skip to content

Instantly share code, notes, and snippets.

@prog893
Last active February 17, 2025 15:28
Show Gist options
  • Save prog893/42c1b005dea3d3443038ba61acf88dec to your computer and use it in GitHub Desktop.
Save prog893/42c1b005dea3d3443038ba61acf88dec to your computer and use it in GitHub Desktop.
CloudFront Signed Cookie generator in Python

CloudFront Signed Cookie generator

For signed URLs, refer here

Usage

from cloudfront_signed_url import generate_cloudfront_signed_url

url = "https://your-cf-domain.com/path/to/file.txt"
cookie = generate_cloudfront_signed_cookie(url, 3600)
print(generate_curl_signed_cookies(url, cookie))

Signed Cookie generation is not implemented in boto3 (only Signed URLs). This gist attempts to make a minimal, simple, independent Signed Cookie generator for CloudFront (or a starting point for more complex logic).

You may use aws_base64_decode method to check generated policies.

Prerequisites

  • Configured CloudFront Distribution
  • An Origin access identity and a CloudFront key
  • Origin and Behavior configured to Restrict Viewer Access

Reference: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html

Parameters

  • Make sure you have a CloudFront key pair and key group created and associated with distribution behavior, details here)
  • Replace newlines with \\n in private key and save the result to an SSM Parameter Store paramater named CF_SIGNED_URL_PRIVATE_KEY
  • Save key ID (key pair ID) to a parameter named CF_SIGNED_URL_KEY_ID

CloudFront Signed Cookies

Signed Cookie consists of:

  • CloudFront-Policy: Access policy, encoded with base64 (RFC-restricted characters replaced)
  • CloudFront-Signature: Access policy, encrypted with a private key and encoded with base64 (RFC-restricted characters replaced)
  • CloudFront-Key-Pair-Id: CloudFront key-pair ID

Access policy must be stripped to not contain any whitespace, and must be a valid JSON.

Notes

  • Unlike S3 pre-signed URLs, you can use cookies generated once multiple times, as long as it is still valid (TTL).
  • You can modify make_policy to make other policies (not per-url, but broader clauses), or even signed cookies (Policy, Signature, Key-Pair-Id are generated in the same way for cookies too).

Dependencies

  • cryptography
  • boto3
@rakshithxaloori
Copy link

@SamuelLeapifai You're welcome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment