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.