Generating Presigned URL for AWS S3 Files

To protect files from being downloaded by anyone with a link to S3 file, we can generate a pre-signed URL with a specified expiration period. I am using the gems aws-sdk-s3 version 1.16.0 and aws-sigv4 version 1.0.3.

class SecureFile
  def self.signed_url    
    Aws.config[:s3] = {
              region: 'us-west-1',
              credentials: Aws::Credentials.new(
                Credential.amazon_access_key_id,
                Credential.amazon_secret_access_key),
              retry_limit: 0
            }
    presigner = Aws::S3::Presigner.new(client: Aws::S3::Client.new)
    params = {
      bucket: "www.joaquinamenabar.com",
      key: 'Video1-10.mov',
      expires_in: 86400
    }
    presigner.presigned_url(:get_object, params)                      
  end  
end

I read the tests for aws-sdk-s3 gem to figure out the basic structure for generating the pre-signed URL. From there, it was just Googling on the error messages to figure out the details of Presigner and Credentials. The view uses HTML5 video tag like this:

<video id="tangoLesson" preload controls controlsList="nodownload">
  <source src="<%= SecureFile.signed_url %>"> 
</video>

The nodownload option prevents Chrome from showing the download icon. You can configure your bucket such that only requests from your domain will be allowed to access the files in your bucket. The files are not public and will give you access denied error.

Note

You must not have any spaces or weird characters, otherwise you will run into errors. In this screenshot, the file with a space results in an error:

S3 File Access Error

You will not be able to stream the video on the browser:

S3 Video Streaming Error

Accessing presigned URL after the expiration time will result in the following error:

expired presigned URL

Reference

AWS Ruby Samples


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.