Chaining Rack Middleware to force SSL and HTTP Basic Authentication

I have been working on a Sinatra application that will live on Heroku. It pulls some sensitive data from Harvest so I wanted to make sure it was secure. Heroku offers free “piggyback” SSL if you use (or for the new Cedar stack) which is fine for this application.

Initially I was pushing the requests to SSL with a redirect on the root URL of the app, but this presented a problem when I wanted to add HTTP Basic authentication, because Rack::Auth::Basic is an all-or-nothing affair.

Fortunately, it proved easy to use Rack::SSL to redirect all requests to SSL and then ask for authentication. This works great because Rack middleware is chained. Best of all, it separates these concerns from my code, making it nice and clean.

I couldn’t find any examples of this, so I wrote up a simple Sinatra app that demonstrates how it works. To see a demo, visit (username: admin / password: password)