Sharing sessions between Rails apps.
March 27th, 2008
Sometimes (in my case 2 times) you may have more than one application running off the same database, partially sharing model code. In the first case I had 4 apps (one main and four satellites) running this way, but the userbase was not shared between them (most users didn’t actually know of the other apps), so common sessions were not needed. In the second case (a distrbuted file sharing network) users floated between the main site and satellites and I wanted to include flash[:notices] while redirecting them. As you know, flash messages are kept in the session, so i needed all the apps to share the session data for the user.
There are 2 things you need to do to share sessions (this applies when using subdomains, i’m not sure if it’s doable with totally different domains).
First: make all the apps use the same session key and secret by editing the environment.rb file:1 2 3 4 |
config.action_controller.session = {
:session_key => '_your_session',
:secret => 'some_long_string_of_letters_and_numbers'
} |
ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS.update(:session_domain => ".yourdomain.com") |
My problem, however, was that this setup worked only one way. I could set session variables in the main app and read from the satellite, but not the other way. As found out later, the problem is that the rails2 default session store is CookieStore. And cookies written by the top level domain can’t be altered by subdomains. To fix this i had to migrate to the ActiveRecord session store.
After a few hours of setting all of this up and testing, I decided that all of this was too much pain and security issues to be used in production, so I’ll just have another way of sending messages between the apps. But I also thought that someone may find this info useful (the CookieStore problem wasn’t evident to me), so I wanted to share it =)

Leave a Reply