HttpOnly Session Cookies using ActiveRecordStore in Rails 2.2

If you’re using CookieStore to manage sessions in your Ruby on Rails application, Rails 2.2 provides the great feature that you’re now able to use HTTPOnly cookies. These are a great benefit because, for compatible web browsers, they dramatically reduce the risk of a Cross Site Scripting (XSS) attack being able to be used to hijack your users’ sessions, which is particularly important on sites displaying user-generated content. You simply have to adjust your environment.rb file with something like:

config.action_controller.session = {
:session_key => ‘_session_id’,
:session_http_only => true,
:secret      => ‘your-secret’
}
config.action_controller.session_store = :cookie_store

Unfortunately, the Rails developers didn’t see fit to extend HTTPOnly cookies to those of us using ActiveRecordStore, where the XSS risk is still just as real. To fill this gap, I’ve produced a very simple and only slightly-hackish plugin which overrides the functionality of Rails’ CGI::Cookie to force all cookies produced by Rails to be HTTPOnly, regardless of the session store being used.

To use it, download this file and extract it into your application’s vendor/plugins directory, and restart your application server. You can test that it’s working using Tamper Data, FireCookie, or whatever your favourite cookie sniffing tool is.

1 comment

  1. Ægir Ægir says:

    Thanks for the patch.

    I did a smal modifycation that uses the rails configuration.

    class CGI::Cookie
    alias :original_initializer :initialize

    def initialize(name = ”, *value)
    http_only = Rails.configuration.action_controller[:session][:session_http_only].nil? ? true : Rails.configuration.action_controller[:session][:session_http_only]

    if name.kind_of?(String)
    original_initializer({‘name’ => name, ‘value’ => value, ‘http_only’ => http_only})
    else
    original_initializer(name.merge({‘http_only’ => http_only}))
    end
    end
    end

Reply here

Your email address will not be published. Required fields are marked *

Reply on your own site

Reply by email

I'd love to hear what you think. Send an email to b1449@danq.me; be sure to let me know if you're happy for your comment to appear on the Web!