Read more

Sharing cookies across subdomains with Rails 3

Deleted user #6
March 03, 2015Software engineer

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

  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

Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

… 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 Show archive.org snapshot at stackoverflow says

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

    :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

    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.

Posted to makandra dev (2015-03-03 17:27)