Sinatra and SSL

November 17, 2011 code 2 min read

I recently rolled out SSL support on is a fairly simple Sinatra application. Most of the app requires authentication, but there are a few public URLs that are unauthenticated.

There two essential steps in securing an app which requires user authentication and then gives them unlimited access to their data:

  1. Only set and use session cookies over secure connections
  2. Mark all cookies as Secure so the browser doesn’t transmit them when requesting a non-secure URL

I evaluated a couple options, but quickly settled on Josh Peek’s simple rack-ssl gem. Rack::SSL is a middleware that just redirects http:// requests to https:// and marks any cookies set by your app as secure.

I wanted to create a clear separation between the parts of that require authentication and those that don’t to avoid accidentally leaking cookies (yeah, that’s a technical term), so I moved all the non-authenticated routes to a separate Sinatra application and insert it into the main app. Here’s essentially what I ended up with:

class Application < Sinatra::Base
  set :ssl, lambda { !development? }

  use PublicApplication
  use Rack::SSL, :exclude => lambda { !ssl? }
  use Rack::Session::Cookie, :expire_after => 1.week, :secret => '…'

  get '/dashboard' do

class PublicApplication < Sinatra::Base
  get '/' do
    'Hello world'
This content is open source. Suggest Improvements.


avatar of Brandon Keepers I am Brandon Keepers, and I work at GitHub on making Open Source more approachable, effective, and ubiquitous. I tend to think like an engineer, work like an artist, dream like an astronaut, love like a human, and sleep like a baby.