【问题标题】:Amazon S3 Query String Authentication Invalid DateAmazon S3 查询字符串身份验证无效日期
【发布时间】:2013-02-14 08:47:00
【问题描述】:

我找到了使用查询字符串身份验证创建指向 Amazon S3 资源的链接的脚本:https://gist.github.com/1032395

由于我没有使用 rails,所以我手动包含了这些库。

每次我尝试使用此脚本生成的 URL 打开资源时,我都会收到“拒绝访问”错误,因为“日期无效(应该是自纪元以来的秒数):1349364847”

有什么想法可以从哪里来?

require 'cgi'
require 'base64'
require 'openssl'

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       = '' # i.e. https://mybucket.s3.amazonaws.com
    bucket            = '' # i.e. mybucket
    access_key_id     = '' # your Amazon S3 access key ID
    secret_access_key = '' # your Amazon S3 secret access key
    expiration_date   = Time.now.utc.to_i + (2*24*60*60) # 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

【问题讨论】:

    标签: ruby amazon-s3


    【解决方案1】:

    我想如果你require 'active_support/core_ext'你可以使用2.days.from_now.utc.to_i

    我为此挣扎了一会儿,最终选择了 aws-sdk: http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/S3/S3Object.html#url_for-instance_method

    require 'aws-sdk'
    
    bucket = "bucketname"
    resource = "myfile.jpg"
    access_key_id = "12345"
    secret_access_key = "abcdef"
    
    s3 = AWS::S3.new(:access_key_id => access_key_id, :secret_access_key = secret_access_key)
    signed_url = s3.buckets[bucket].objects[resource].url_for(:read).to_s
    

    注意:url_for 也有一个:expires 选项,默认为一小时。

    【讨论】:

      猜你喜欢
      • 2013-09-14
      • 1970-01-01
      • 1970-01-01
      • 2010-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-17
      • 2016-12-25
      相关资源
      最近更新 更多