Skip to content

Instantly share code, notes, and snippets.

@iwasrobbed
Created June 17, 2011 21:29
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save iwasrobbed/1032395 to your computer and use it in GitHub Desktop.
Save iwasrobbed/1032395 to your computer and use it in GitHub Desktop.
Amazon S3 Query String Authentication for Ruby on Rails
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
@iwasrobbed
Copy link
Author

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

@jhorsch
Copy link

jhorsch commented May 2, 2015

Has there been an update to match the criteria shown at http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html

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