Skip to content

Instantly share code, notes, and snippets.

@rtircher
Created September 12, 2013 03:31
Show Gist options
  • Select an option

  • Save rtircher/6532787 to your computer and use it in GitHub Desktop.

Select an option

Save rtircher/6532787 to your computer and use it in GitHub Desktop.
Generate authenticated url for S3 in ruby
class S3QueryStringAuthenticationBuilder
def initialize(bucket, access_key, secret_key)
@bucket = bucket
@access_key = access_key
@secret_key = secret_key
end
def build_query_string_authentication(file_url, time_to_live=1.minute)
file_url = "/#{file_url}" unless file_url.start_with?('/')
expires = (Time.now.utc + 1.minutes).to_i
signature = build_signature(@secret_key, canonicalized_resource(file_url), expires)
"#{host}#{file_url}?AWSAccessKeyId=#{@access_key}&Expires=#{expires}&Signature=#{signature}"
end
def host
"https://#{@bucket}.s3.amazonaws.com"
end
private
def canonicalized_resource(file_url)
"/#{@bucket}#{file_url}"
end
def build_signature(secret_key, canonicalized_resource, expires)
utf8 = Encoding.find('UTF-8')
url_encode( base64( hmac_sha1(secret_key, string_to_sign(canonicalized_resource, expires).force_encoding(utf8) ) ) )
end
def string_to_sign(canonicalized_resource , expires)
"GET\n\n\n#{expires}\n#{canonicalized_resource}"
end
def hmac_sha1(secret_key, string)
OpenSSL::HMAC.digest( OpenSSL::Digest::SHA1.new, secret_key, string )
end
def base64(string)
Base64.strict_encode64(string)
end
def url_encode(string)
URI.encode(string)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment