Skip to content

Instantly share code, notes, and snippets.

@bunnymatic
Created February 28, 2014 16:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bunnymatic/9274108 to your computer and use it in GitHub Desktop.
Save bunnymatic/9274108 to your computer and use it in GitHub Desktop.
Build signed read url for s3/aws access outside of the aws-sdk#url_for which doesn't like filenames with w/spaces
module MyProject
class S3
def config
Rails.application.config.s3_config
end
def url_for_read(path, opts)
expire_date = (Time.zone.now + opts[:expires]).to_i
request_string = "GET\n\n\n#{expire_date}\n/#{config[:bucket]}/#{path}"
hmac = OpenSSL::HMAC.digest(digest, config[:secret_access_key], request_string)
signature = URI.escape(Base64.encode64(hmac).strip)
s3_url_domain + "#{path}?AWSAccessKeyId=#{config[:access_key_id]}&Expires=#{expire_date}&Signature=#{CGI::escape(signature)}"
end
private
def s3_url_domain
"https://#{config[:bucket]}.s3-#{config[:region]}.amazonaws.com/"
end
def digest
OpenSSL::Digest::Digest.new('sha1')
end
end
end
@alfondotnet
Copy link

alfondotnet commented Aug 3, 2016

In my case, the <StringToSign> was expecting 2 new lines (not 3), following the content type. The response from the AWS servers is pretty helpful in this case.

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