Skip to content

Instantly share code, notes, and snippets.

@t11a
Last active July 25, 2017 06:07
Show Gist options
  • Save t11a/06965f6aa87569f78b3a to your computer and use it in GitHub Desktop.
Save t11a/06965f6aa87569f78b3a to your computer and use it in GitHub Desktop.
CloudFront - Signed Cookies Using a Custom Policy
#!/usr/bin/env ruby
require 'json'
### CloudFront Key Pair
KEY_PAIR_ID = "XXXXX"
PRIVATE_KEY = "pk-XXXXX.pem"
### Destination URL and RESOURCE for Policy
DST_URL = "https://xxxx.cloudfront.net/index.html"
RESOURCE = "http*://xxxx.cloudfront.net/index.html"
start_time = (Time.now - 60).to_i
expire_time = (Time.now + 60*60*24*10).to_i
condition = { "DateLessThan" => {"AWS:EpochTime" => expire_time }, "DateGreaterThan" => {"AWS:EpochTime" => start_time } }
policy = { "Statement" => ["Resource" => RESOURCE, "Condition" => condition] }
puts "------- policy -------"
p policy = policy.to_json
puts "------- encoded_policy -------"
encoded_policy = `printf %s '#{policy}' | base64 | tr '+=/' '-_~'`
p encoded_policy.gsub!(/(\r\n|\r|\n)/, "")
# cat policy.json | openssl sha1 -sign pk.pem | openssl base64 | tr '+=/' '-_~'
signature = `printf %s '#{policy}' | openssl sha1 -sign #{PRIVATE_KEY} | openssl base64 | tr '+=/' '-_~'`
puts "------ signature --------"
p signature.gsub!(/(\r\n|\r|\n)/, "")
header = "Cookie:CloudFront-Expires=#{expire_time}; CloudFront-Policy=#{encoded_policy}; CloudFront-Signature=#{signature}; CloudFront-Key-Pair-Id=#{KEY_PAIR_ID}"
puts "-------- header -------"
p header
puts "---------------"
puts `curl -vH '#{header}' #{DST_URL}`
@t11a
Copy link
Author

t11a commented Jun 12, 2015

Prerequisite

  • CloudFront Distribution and the Settings
  • Create CloudFront Key Pair

@t11a
Copy link
Author

t11a commented Jun 12, 2015

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