Configuring Rails App to handle multiple subdomains and multiple cookies
Asked Answered
M

2

5

I have a rails app which supports multiple domains and each domain may have multiple subdomains.

Users visiting mydomain1.com do not receive the same experience as mydomain2.com (although the base behaviour of the apps is the same)

Therefore, if a user is logged in to mydomain1.com, it shouldn't then be logged in to mydomain2.com

If a user is logged in to france.mydomain1.com, it should then be logged in to germany.mydomain1.com

Previously, I've handled this by setting the domain in the session store configs:

MyApp::Application.config.session_store :cookie_store, :key => '_MyApp_session', :domain => APP_CONFIG[:domain]

I'm trying to work out the best way to handle this with multiple domains?

I've tried hacking around ActionDispatch::Callback but the request is not available from within there.

Can anybody suggest a good way of supporting multiple cookies from within one app?

Ideally I'd like to create a fresh cookie for each subdomain.

Monogamist answered 17/5, 2011 at 7:51 Comment(2)
Have you tried it yet? It shouldn't be an issue since cookies are only valid for the domain that set them. I have a similar setup with no problems.Sextant
I haven't tried it in a live setup yet... I need to edit my question though as there's more to the problem.Monogamist
C
5

You should do that:

class ActionDispatch::Session::MultiDomainStore < ActionDispatch::Session::CookieStore
  def initialize(app, options = {})       
    super(app, options.merge!(:domain => compute_domain(app)))      
  end

  def compute_domain(app)
    ...
  end
end

MyApp::Application.config.session_store :multi_domain_store, :key => '_MyApp_session'

I.e. your domain should start with the dot.

Cubby answered 17/5, 2011 at 11:49 Comment(2)
I can't specify just one domain - the app should support many domains and many subdomainsMonogamist
Then you should create custom session store. See updated answerCubby
S
2

It shouldn't be an issue as cookies are only valid per domain. You can have a _MyApp_session for example1.com and one for example2.com. The cookies are managed by the browser and only sent to the host if the domain matches.

Say you visit example1.com and log in and you will get a cookie with the value abcdef123. Then you log into example2.com and you will get another cookie with a random string uvwxyz890.

If you return to example1.com later, the browser will only send the cookies that are valid for this domain to your app. Your app won't have to manage anything and you don't have to hack anything.

Sextant answered 17/5, 2011 at 8:40 Comment(1)
The problem is that I want cookies to be shared across each subdomain - but not each domain.Monogamist

© 2022 - 2024 — McMap. All rights reserved.