public
Last active

Amazon S3 Query String Authentication for Ruby on Rails

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
def generate_secure_s3_url(s3_key)
#
# s3_key would be a path (including filename) to the file like: "folder/subfolder/filename.jpg"
# but it should NOT contain the bucket name or a leading forward-slash
#
# this was built using these instructions:
# http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?S3_QSAuth.html
# http://aws.amazon.com/code/199?_encoding=UTF8&jiveRedirect=1
s3_base_url = MyApp::Application::S3_BASE_URL # i.e. https://mybucket.s3.amazonaws.com
bucket = MyApp::Application::S3_BUCKET # i.e. mybucket
access_key_id = MyApp::Application::S3_ACCESS_KEY_ID # your Amazon S3 access key ID
secret_access_key = MyApp::Application::S3_SECRET_ACCESS_KEY # your Amazon S3 secret access key
expiration_date = 2.days.from_now.utc.to_i # 2 days from now in UTC epoch time (i.e. 1308172844)
 
# this needs to be formatted exactly as shown below and UTF-8 encoded
string_to_sign = "GET\n\n\n#{expiration_date}\n/#{bucket}/#{s3_key}".encode("UTF-8")
 
# we have to CGI/URL escape the signature since it would fail if it included / or + characters
signature = CGI.escape( Base64.encode64(
OpenSSL::HMAC.digest(
OpenSSL::Digest::Digest.new('sha1'),
secret_access_key, string_to_sign)).gsub("\n","") )
return "#{s3_base_url}/#{s3_key}?AWSAccessKeyId=#{access_key_id}
&Expires=#{expiration_date}
&Signature=#{signature}"
end

Keep in mind that .encode("UTF-8") is a Ruby 1.9+ capability.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.