Read more

Distribute files from a private bucket on AWS S3

Thomas Eisenbarth
September 17, 2012Software engineer at makandra GmbH

Given you store files on Amazon S3 and you need to stream those files out to people while you don't want them to be able to distribute the content simply by sharing the S3 URL.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

You could either mark the bucket as private and fetch the appropriate files from S3 to your application server and stream them to the client finally. While this is possible, I'd recommend to use what AWS calls "Query String Authentication" Show archive.org snapshot .

If you're using Paperclip you can chose between two storage adapters (S3 and Fog) that are both capable of handling that for you.
See and documentation Show archive.org snapshot .

irb(main):003:0* your_model.document.public_url
=> "https://your-bucket.s3.amazonaws.com/files//foo/bar/123/456/ab/cd/1/2/3/original/Attachment.pdf"

irb(main):004:0> your_model.document.expiring_url
=> "http://s3-eu-west-1.amazonaws.com/your-bucket/files/foo/bar/123/456/ab/cd/1/2/3/original/Attachment.pdf?AWSAccessKeyId=ABSJASHJK232JAHBS&Signature=V6aJhal2kaB4bxKal23lSMV%2F9w%3D&Expires=1347889426"

The expiring_url method carries out a web service call to S3 to gain the data for AWSAccessKeyId and Signature being used within the URL. So you should not include those links within views but only when the document is requested, i.e. link to attachments/:id and receive + redirect to the expiring_url when the show method of your AttachmentsController.

Posted by Thomas Eisenbarth to makandra dev (2012-09-17 15:01)