当我从Amazon S3打开签名URL时,为什么会拒绝访问?

时间:2013-06-28 20:00:15

标签: ruby-on-rails ruby amazon-s3

我需要从Amazon S3打开已签名的URL,并且我一直拒绝访问。

例如,访问此网址:

https://aidin.s3.amazonaws.com/aidin/staging/attachments/faxattach/94DD749z65ejkh353?AWSAccessKeyId=AKIAJPBOMKHDQ5WNJM3Q&Expires=1373047778&Signature=Y%2F968F9LIfkfHwsp7T8P0CqjQhQ%3D

从这段代码:

 def download path
    local_file = File.new 'attachment' + (Time.now.strftime("%Y%m%d%H%M%S")+(rand * 1000000).round.to_s) + ".pdf", 'wb+'
    # HTTPError is caught in the /process in faxattach.rb
    uri = URI.parse(path)
    http_object = Net::HTTP.new(uri.host, uri.port)
    http_object.use_ssl = true if uri.scheme == 'https'
    request = Net::HTTP::Get.new uri.request_uri
    http_object.start do |http|
      response = http.request request
      local_file.write(response.read_body)
    end
    debugger
    local_file.rewind
    local_file
  end

我在local_file

中收到此信息
<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Error><Code>AccessDenied</Code><Message>Access Denied</Message><RequestId>11A4FB2DF920A272</RequestId><HostId>6qH/f602NxfJa38oW+67Q+5GVx5XD+BJqTzNVR5IhhnvEDhiXUoTR0K90/quZTWk</HostId></Error>

有谁知道为什么?网址在我的浏览器中正常打开,我需要额外的查询参数,例如AWSAccessKeyIDExpires等,这些都是出于安全原因。

2 个答案:

答案 0 :(得分:0)

我会简化并使用OpenURI:

require 'open-uri'
url = "http://aidin.s3.amazonaws.com/aidin/staging/attachments/faxattach/94DD749z65ejkh353?AWSAccessKeyId=AKIAJPBOMKHDQ5WNJM3Q&Expires=1373047778&Signature=Y%2F968F9LIfkfHwsp7T8P0CqjQhQ%3D"

File.open( 'attachment' + (Time.now.strftime("%Y%m%d%H%M%S")+(rand * 1000000).round.to_s) + ".pdf", 'wb+') do |file|
  file << open(url).read
end

答案 1 :(得分:0)

您想要request = Net::HTTP::Get.new(path)

我在上下文中的测试:

require 'net/http'
path = "https://aidin.s3.amazonaws.com/aidin/staging/attachments/faxattach/94DD749z65ejkh353?AWSAccessKeyId=AKIAJPBOMKHDQ5WNJM3Q&Expires=1373047778&Signature=Y%2F968F9LIfkfHwsp7T8P0CqjQhQ%3D"
uri = URI.parse(path)
http_object = Net::HTTP.new(uri.host, uri.port)
http_object.use_ssl = true if uri.scheme == 'https'
request = Net::HTTP::Get.new(path)
http_object.start do |http|
  response = http.request request
  puts response.read_body
end