Setting the session base domain in Rails 2.3

Prior to Rails 2.3, you could set the session base domain as follows:

ActionController::Base.session_options[:session_domain] = '.example.com'

In Rails 2.3, this needs to change to:

config.action_controller.session[:domain] = '.example.com'

I usually set this in my config/environments/.rb configuration files but it could be set in config/environment.rb if you want it to apply across configurations.

Background

This setting will allow for a shared session across multiple subdomains.

This is useful where you want a user to login at www.example.com and then be able to remain logged in when accessing user.example.com

Comments (5)

doug liveseyMay 13th, 2009 at 18:26

Hi — if you set this in two apps (running on the same server) would they be able to share a session?
Cheers,
Doug.

Andrew TimberlakeMay 14th, 2009 at 05:04

Yes, if you’re using cookie based sessions and both apps had the same session_key and secret.
This could be done if they’re running on different servers.
Both applications would obviously need to share the same base domain i.e. app1.example.com and app2.example.com

Hani elabedMay 21st, 2009 at 06:34

Hi,
Thanks, this was very helpful for me in Cucumber and my Ubuntu VIM environment.
You script is great and we added it to features/support/env.rb, but it broke the Mac OS version, so here is my humble suggestion for improving your script so that it can work on both Mac OS 10 as well as Linux.

module Webrat::SaveAndOpenPage
alias_method :old_open_in_browser, :open_in_browser
def open_in_browser path
if ruby_platform =~ /linux/i
`firefox #{path}`
else
old_open_in_browser path # notice how I added ‘path’ in here, it was missing in your original post.
end
end
end

Andrew TimberlakeMay 21st, 2009 at 08:00

Thanks Hani

I think you’ve commented on the wrong post though.
I have updated the code at http://ramblingsonrails.com/using-webrats-save_and_open_page-on-linux

Bill HorsmanJune 13th, 2009 at 19:55

For the record, I’m sharing domains across two apps using a similar technique. But rather than using cookie based sessions I’ve got a separate database and have the session table configured to use it. In environment.rb:

config.action_controller.session_store = :active_record_store
CGI::Session::ActiveRecordStore::Session.establish_connection “myshareddb_#{RAILS_ENV}”

It’s working pretty well, and you get all the advantages of a database session. Of course, your apps need to be running close enough to make sharing a database feasible. (Mine are running on the same server).