Httponly cookies in Rails

Why should you set the httponly flag for cookies, especially the session cookie? If it’s set, modern browsers won’t return this cookie in the JavaScript document.cookie method anymore. Before browsers added support for this flag, there was a danger of cookie theft if somebody found an XSS vulnerability and thus could run JavaScript in the security context of your application. If that was too quick, here’s how sessions work.

How to send the flag?

If you’ve a file called config/session_store.rb including this line (Rails 3+), then it’s automatically set already.

Rails.application.config.session_store :cookie_store, key: '_app_session'

You could add httponly: true to be explicit. In Rails 2 the key was :http_only

ActionController::Base.session = {
 :key => '_app_session',
 :http_only => true

What about other cookies that aren’t session cookies?

Other cookies, that are read and written using ActionController#cookies, don’t have the HttpOnly flag set by default. That means you still need to add the flag here manually: