ruby-on-railssessionruby-on-rails-5multiple-domains

How do I maintain session in Rails app with support for multiple domains?


Here's the scenario:

I have a Rails app running on a single machine. The app for the sake of this discussion is a content management system and will be used to serve multiple sites in a network. It can be reached at app.com. Users should be able to setup a custom domain for their site.

What I'm struggling with is how to maintain the session so that a user only has to sign into the network once. If they visit any site on the network, their session should be maintained. (Technically, the user is still on the same site just with a custom URL for the site their visiting.)

How do I maintain the session for the user across all sites on the app?

Based on what I've read about cookies, this is difficult b/c cookies cannot be shared between unique domains. What I'm looking for is help understanding the parts of the problem at play. I'm game to write Rack Middleware or add other tech in front of the app if that's what it takes. Eventually, I'd like to make it possible for each of these domains to use HTTPS, but let's start leave that out for now.


Solution

  • You can transfer sessions through a series of redirects.

    Let's say you have an app with the domain of platform.com and you host custom domains such as customdomain.com on this platform. As described in the question, whenever a user is logged in on platform.com they should be logged in on all hosted domains.

    The basic idea works like this:

    1. User signs in to platform.com
    2. User requests a page on customdomain.com
    3. App server sees the request from the customdomain.com and sees that the user is not logged in to customdomain.com.
    4. App server redirects to platform.com/get_session?redirect=customdomain.com
    5. App server redirects to customdomain.com/set_session?login_token=<HASH>
    6. App server sets session cookie in response to set_session

    Voila!! The user's session is now transferred from platform.com to customdomain.com.

    Caveat: The challenge here is in the details of when the app decides to redirect. You need to add logic to ensure you don't end up in an infinite redirect cycle.