tl;dr: Use @Nader's code. BUT I found I needed add it into my conifg/environments/[production|development].rb
and pass my dot-prefixed-domain as an argument. This is on Rails 3.2.11
Cookie sessions are usually stored only for your top level domain.
If you look in Chrome -> Settings -> Show advanced settings… -> Privacy/Content settings… -> All cookies and site data… -> Search {yourdomain.example}
You can see that there will be separate entries for sub1.yourdomain.example
and othersub.yourdomain.example
and yourdomain.example
The challenge is to use the same session store file across all subdomains.
##Step 1: Use @Nader's CustomDomainCookie
code##
This is where Rack Middleware comes in. Some more relevant rack & rails resources:
Basically what this does is that it will map all of your cookie session data back onto the exact same cookie file that is equal to your root domain.
##Step 2: Add To Rails Config##
Now that you have a custom class in lib, make sure are autoloading it. If that meant nothing to you, look here: Rails 3 autoload
The first thing is to make sure that you are system-wide using a cookie store. In config/application.rb
we tell Rails to use a cookie store.
# We use a cookie_store for session data
config.session_store :cookie_store,
:key => '_yourappsession',
:domain => :all
The reason this is here is mentioned here is because of the :domain => :all
line. There are other people that have suggested to specify :domain => ".yourdomain.example"
instead of :domain => :all
. For some reason this did not work for me and I needed the custom Middleware class as described above.
Then in your config/environments/production.rb
add:
config.middleware.use "CustomDomainCookie", ".yourdomain.example"
Note that the preceding dot is necessary. See "https://mcmap.net/q/212371/-sub-domain-cookies-sent-in-a-parent-domain-request" for why.
Then in your config/environments/development.rb
add:
config.middleware.use "CustomDomainCookie", ".lvh.me"
The lvh.me trick maps onto localhost. It's awesome. See this Railscast about subdomains and this note for more info.
Hopefully that should do it. I honestly am not entirely sure why the process is this convoluted, as I feel cross subdomain sites are common. If anyone has any further insights into the reasons behind each of these steps, please enlighten us in the comments.