Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make rack session cookies httponly?

I am using Ruby and Sinatra to develop an application.
I use

enable :sessions

in order to use the session variable provided by rack. How can I make all of the session cookies be HTTPOnly? Is it like this by default? I can't find any documentation on this.

like image 282
Lev Dubinets Avatar asked Feb 20 '23 05:02

Lev Dubinets


1 Answers

Instead of enable :sessions:

use Rack::Session::Cookie, {:httponly => true }

I'd suggest using the encrypted_cookie gem instead, it's far more secure. As an example, here's what I'll probably have for a project:

# app/main.rb
module Example
  class App < Sinatra::Base # this class in its own file
    # stuff here
  end
end

# app/config.rb
require "main"
module Example
  def self.app #
    Rack::Builder.app do
      cookie_settings = {        
        :key          => 'usr',
        :path         => "/",
        :expire_after => 86400,             # In seconds, 1 day.
        :secret       => ENV["COOKIE_KEY"], # load this into the environment of the server
        :httponly     => true
      }
      cookie_settings.merge!( :secure => true ) if ENV["RACK_ENV"] == "production"

      # AES encryption of cookies
      use Rack::Session::EncryptedCookie, cookie_settings

      # other stuff here

      run App
    end
  end
end

# config.ru
require "app/config"
run Example.app  # this in the rackup file

(To clarify why I've laid it out this way - this kind of stucture allows me to split the app up and use it easier in tests by just requiring the app/config.rb. YMMV)

like image 132
ian Avatar answered Mar 03 '23 20:03

ian