Secure asset URLs with rails


I did some searching and didn’t find anything covering this, so hopefully this isn’t a dupe. Anyway, I’m working on an app where customers can buy a downloadable product, a zip file. Now, ideally this url would be secure or maybe even bound to a unique purchase for that user… maybe a method that checks to see if the user has purchased that item and then creates a link for them. This way someone can’t buy one zip and then share it with everyone they know.

Would anyone have any advice to get me started in the right direction?

Before you jump into coding, have you considered an off-the-shelf solution such as or ?

Too late! There’s a lot more to the app and what you are purchasing (icon sets/illustrations) are part of the app in that you can search them by name, tags, sets, etc.

It’s nearly finished, I’m just tying up some of the loose ends :smile:

I came accross this topic in the book Rails 4 in action ( ) 9.3 Serving files through a controller

There they serve uploaded files through a controller, this controller will check that the user attempting to access a file has permission to do so before serving the file.

hope this helps,


Hey Anthony,

That’s exactly what I ended up doing. I created a downloads controller that handles the request, a method on the user model to check to see if that user owns the product, and then serve up the file if everything checks out. If the user isn’t logged in, then they are redirected to the login screen and if they dont own it I respond with a 402 Requires Payment status!

I followed along the demo-application in Rails 4 in action. The code can be found here:

more specifally, the attachments_controller that serve the secured attachments can be found here:


That looks pretty close to what I did. Not as complicated as I initially thought!

a bit of a hijack from the original thread topic, but Rails 4 in Action is a pretty solid overview in general. The first 10 chapters are pretty standard Rails CRUD, but once Pundit comes along, I’d say it’s worth it’s weight from there on.

Now, from a style perspective it might not pass, say, Hound’s muster, but if you walk in with an educated understanding of general rails testing and a knowledge of the testing phases, I’d recommend it.