Question

Setup

I have a Rails application where users register for an account, and a subdomain is created for them. They can then proceed to the subdomain and log in with their credentials. The workflow looks something like this:

  1. User visits base domain fills out a form that with email/username/password and subdomain fields
  2. From the submitted info, the server creates an account in the global/public database. Server then creates a database that will be specific to that particular subdomain/account, and stores the user record in it.
  3. User is redirected to their subdomain, and asked to log in.

(note: to implement the separate "databases", I'm using postgres schemas, but that should be irrelevant.)

The question

My question involves step 3. I would like to redirect the user to their subdomain and log them in automatically instead of asking them to log in. However, I do not want to share a single session across all of the subdomains.

I would like to somehow securely transmit auto login request.

Possible Solution

I have considered using a single-use, random token that I would store in a cookie and in the users table. After the user successfully creates an account, he would be redirected to the subdomain. At that point the token would be consumed/destroyed and the user would be automatically logged in.

I would also need to have a short window for the token to be used before expiring.

Thoughts? Thanks!

Was it helpful?

Solution

I had the same issue, the possible solution you suggest does not work because the session is not shared between subdomains.

I solved it the following way (same idea you propossed, different implementation):

  • Create a new model (I called it LoginKey) that contains the user_id and a random SHA1 key.
  • When the user is authenticated at the parent domain (for example: mydomain.com/users/sign_in), a new LoginKey is created and the user is redirected to the corresponding subdomain to an action that I called login_with_key (for example: user_subdomain.mydomain.com/users/login_with_key?key=f6bb001ca50709efb22ba9b897d928086cb5d755322a3278f69be4d4daf54bbb)
  • Automatically log the user in with the key provided:

    key = LoginKey.find_by_login_key(params[:key])

    sign_in(key.user) unless key.nil?

  • Destroy the key:

    key.destroy

I didn't like this solution 100%, I tried out a lot of different approaches that do not require a db record to be created, but always faced security concerns, and I think this one is safe.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top