Created
February 28, 2014 16:28
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.