0

Say I'm running a multi-tenant application that gives each organization its own portal via a subdomain.

Example -

  • orgA.application.com
  • orgB.application.com
  • etc...

Each subdomain reads from a different schema/tenant in my PSQL db, but is otherwise the same application.

In my ApplicationController I set the current_user as -

def current_user
  if session[:user_id]
    @current_user ||= User.find_by_id(session[:user_id])
  end
end

There are few admin/superusers such as myself that have a user account on each subdomain. If I log into orgA with my user (id = 22), then my session gets set as user_id: 22.

Now say I want to switch over to orgB, where my user id is 44. If I log into orgB after having set my session in orgA, is there any chance I could accidentally log myself in as the user who is 22 on orgB?

More fundamentally, I'm trying to understand how a browser cookie session is set. From my understanding, it's a hash of variables that are encrypted and cached in the client's browser. Is that set per subdomain? Or do all subdomains of a particular site share the same cache/session cookie?

More importantly, how do I prevent cross pollination of sessions like in the example above? Is my current_user method too basic?

Thanks!

user2490003
  • 10,706
  • 17
  • 79
  • 155

1 Answers1

1

You're fundamentally asking about cookies here, to which the answer is relatively simple: cookies are not shared across subdomains unless you explicitly request it.

When you send the Set-Cookie HTTP header to create a cookie in the user's browser, you can choose whether or not to include a domain configuration option. That option controls which domain the cookie saves under and will be served to.

By default, if you send Set-Cookie with no domain option, the cookie will be set for the current hostname, which includes subdomains. That is, a cookie set on siteA.example.com will not be accessible to siteB.example.com.

If you send a domain option of example.com when you create your cookie on siteA.example.com, then the cookie will be accessible on both example.com and *.example.com, so all your sites will be able to access it.

For your situation, then, you should send the Set-Cookie header with no domain option. That's the default in most setups, including Rails so it's unlikely you need to do anything.

Community
  • 1
  • 1
ArtOfCode
  • 5,702
  • 5
  • 37
  • 56