How to Generate a Secure URL to Download File from s3 Using Ruby aws/s3 Gem

10,124

What you need a called a "Tokenized Link". Fortunately, it's built into the aws-sdk gem you are using.

Here's a previous question that a solution you can use:

How to store data in S3 and allow user access in a secure way with rails API / iOS client?

However, that is a Rails solution which has the fancy Rails time helpers like 20.minutes.from_now. You can either set the expiry date to a specific date by adding a specific number of seconds to the current time like Time.now.to_i + (20 * 60), or include the ActiveSupport time helpers into your ruby script with require 'active_support/core_ext/numeric/time'. That will allow the 20.minutes.from_now stuff to work.

Also, you will need to require the entire aws-sdk gem, not just the S3 part.

Share:
10,124
LFoos24
Author by

LFoos24

Updated on June 18, 2022

Comments

  • LFoos24
    LFoos24 almost 2 years

    I am writing a small script to locate a specific file in a bucket on aws and create a temporarily authenticated url to send to colleagues. (Ideally, this would create a result similar to right-clicking a file in a bucket on the console and copying the link address).

    I have looked into paperclip, which doesn't appear to meet this criteria, however I could just not be aware of its full capabilities.

    I tried the following:

    def authenticated_url(file_name, bucket)
      AWS::S3::S3Object.url_for(file_name, bucket, :secure => true, :expires => 20*60)
    end
    

    Which produced this type of result:

    ...-1.amazonaws.com/file_path/file.zip.AWSAccessKeyId={key}Expires=1200&Signature={...}

    Is there a way to create a secure url more similar to the scenario described above that could simply be sent as a link? If not, any secure alternatives would be welcomed.

  • LFoos24
    LFoos24 about 11 years
    Thanks for the direction, however I am getting "NoMethodError: undefined method minutes' for 20:Fixnum" when I run that solution, and subsequently "NoMethodError: undefined method url_for`" when I remove minutes.from_now. Is this because I am using "require 'aws/s3'" and "require 'aws-sdk'"? (I apologize if this is a novice question, I'm still very new to this. I appreciate your patience)
  • Nick Messick
    Nick Messick about 11 years
    Ah, I missed where this was a script, and not Rails. Let me try some things and I'll update my answer.