Reputation: 11069
I have a Rails3 app that uses subdomains. To allow logins etc. to work across all subdomains, I do this in config/initializers/session_store.rb
MyApp::Application.config.session_store :cookie_store, :key => '_myapp_session', :domain => :all
When I deploy my app to Heroku, this works perfectly. I can login and stay logged in across subdomains.
However, when developing locally, this does not work.
My browser does set the session cookie properly:
$ curl http://test.lhs.com/users/sign_in
...
Set-Cookie: _myapp_session=BAh...3ed; domain=.lhs.com; path=/; HttpOnly
...
However, my browser (I tried Safari, FireFox and Chrome) does not set this cookie. So, when I log in I get an InvalidAuthenticityToken
error.
I've tried removing the :domain => :all
part, which does set the session cookie properly, but only for the current subdomain. Setting it explicitly like this :domain => '.lhs.com'
also does not set the cookie.
I'm at a loss here. Why does this work in production on heroku, but not locally. I've even tried different servers (Webrick with rails server
and passenger-standalone). I've also tried running locally on port 80 instead of 3000, but this also makes no difference.
Any clues why the session cookie is not set locally? Thanks!
Upvotes: 5
Views: 6387
Reputation: 4242
Use custom session store config in production only
if Rails.env.production?
Rails::Application.config.session_store(:cookie_store, key: '_my_session', secure: Rails.env.production?, domain: :all, tld_length: 2)
end
Upvotes: 0
Reputation: 76
In config/intializers/session_store.rb set your domain to use all subdomains
Your::Application.config.session_store :cookie_store,
:key => '_example.com_session',
:domain => ".lvh.me"
Make sure to include the .
before the host name.
Upvotes: 1
Reputation: 24551
There is a bug in Rails where :domain => :all
is broken when visiting the site as localhost
or an IP address:
It looks like a patch has been submitted, but I can't tell from that page whether it has been included in any releases yet.
As you've discovered, a solution is to edit /etc/hosts to include something like localhost.localdomain or something else besides a bare hostname (like lhs.me).
Upvotes: 2
Reputation: 41
When :domain => :all
is set in Rails 3.0.3, local session cookies seem not to be set unless you specify a top-level domain in the browser. This may be as designed, though I see no documentation either way.
So your session will fail when you visit localhost, but it should be set normally at mylaptop.local. The ".local" seems to satisfy the requirement for a TLD.
Upvotes: 4
Reputation: 11069
I'm not sure what the problem was here, but I've changed 'lhs.com' to 'lhs.me' and moved it below the official localhost definition in my hosts file. Not it all works like a charm.
Upvotes: 1