Rails 3 additional session configuration options (key, expires_after, secure)

shedd picture shedd · Jun 18, 2011 · Viewed 18.2k times · Source

Can someone point out what the new Rails 3.x session configuration options are?

I'm trying to duplicate the same configuration that I have in my Rails 2.3.x application.

This is the configuration that I used in the application:

#environment.rb
config.action_controller.session_store = :active_record_store

config.action_controller.session = {
    :key         => '_something', #non-secure for development
    :secret      => 'really long random string'
  }


# production.rb - override environment.rb for production
config.action_controller.session = {
  :key            => '_something_secure',
  :secret         => 'really long random string',
  :expire_after   => 60*60,#time in seconds
  :secure         => true #The session will now not be sent or received on HTTP requests.
}

However, in Rails 3.x, I can only find mention of the following:

AppName::Application.config.session_store :active_record_store

AppName::Application.config.secret_token = 'really long random string'

AppName::Application.config.cookie_secret = 'another really long random string'

Are there other config settings to control the key, expire_after time, and secure option?

Regarding the latter, if "config.force_ssl = true" is set in production.rb, I assume the secure option is no longer required?

Thanks very much!

Answer

fidothe picture fidothe · Feb 14, 2012

You now configure the Cookie-based session store through an initializer, probably in config/initializers/session_store.rb. In Rails 3 the session store is a piece of middleware, and the configuration options are passed in with a single call to config.session_store:

Your::Application.config.session_store :cookie_store, :key => '_session'

You can put any extra options you want in the hash with :key, e.g.

Your::Application.config.session_store :cookie_store, {
  :key =>           '_session_id',
  :path =>          '/',
  :domain =>        nil,
  :expire_after =>  nil,
  :secure =>        false,
  :httponly =>      true,
  :cookie_only =>   true
}

(Those are just the standard defaults)

If you force SSL in production then setting secure on the cookie shouldn't really make a difference in practice, but you might want to set it just to be on the safe side...

Your::Application.config.session_store :cookie_store, {
  :key =>           '_session_id',
  :secure =>        Rails.env.production?
}