Posted almost 4 years ago. Visible to the public.

Sharing cookies across subdomains with Rails 3

To achieve this goal you have to setup the session store like the following example:

Copy
MyApp::Application.config.session_store( :cookie_store, { :key => '_myapp_session', :domain => :all, # :all defaults to da tld length of 1, '.web' has length of 1 :tld_length => 2 # Top Level Domain (tld) length -> '*.myapp.web' has a length of 2 } )

The invconvenient side effect for local development

… or: Why do I get "Can't verify CSRF token authenticity" even if csrf token is present?

As :domain => :all is set in Rails 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.

A higher rated answer at stackoverflow says

Copy
As it turns outs 'domain: all' creates a cookie for all the different subdomains that are visited during that session (and it ensures that they are passed around between request). If no domain argument is passed, it means that a new cookie is created for every different domain that is visited in the same session and the old one gets discarded.

In my case, surprisingly I could set cookies with Firefox [v35.0.1] but not with Google Chrome [v40.0.2214.111 (64-bit)]. Even so I've read a lot of posts where people couldn't set cookies with any browser at all.

Solutions

  • Use a dns wildcard service like lvh.me and set

    Copy
    :domain => 'lvh.me' if Rails.env.development?

    Then you can access your local server with lvh.me:3000 or anysubdomain.lvh.me:3000.

  • Another way is, to add mysub.domain.web to /etc/hosts like

    Copy
    127.0.0.1 localhost mysub.domain.web
  • Some developers suggest to write a rack middleware, but at the moment I neither can judge the necessity nor the level of sophistication for that suggestion.

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Martin Straub
Last edit:
over 3 years ago
by Martin Straub
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Martin Straub to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more