David Morales
David Morales

Reputation: 18064

How to share session from a subdomain to another subdomain?

I have a login form that points to secure.example.com, it initializes the session and then redirects to www.example.com

When redirected, the session is not created. Going back to secure.example.com then the session is created. Is this a limitation of how cookies work as I think?

Of course I have added the domain: :all in session_store, with the same result.

I'm using Ruby on Rails 3.2

Upvotes: 2

Views: 320

Answers (3)

David Morales
David Morales

Reputation: 18064

My configuration was fine, as I configured domain: :all, and that's all what it's needed.

The problem in my case was that I had to define the domain: :all in all my cookies, like this:

cookies[:new_cookie] = { :value => "value", domain: :all }

And when deleting them:

cookies.delete :new_cookie, domain: :all

After this change, everything works as expected.

Upvotes: 1

vijikumar
vijikumar

Reputation: 1815

You can set the same session_key in both apps. In appA environment.rb change the session_key, like this

Rails::Initializer.run do |config|
  ...  
   config.action_controller.session = {
   :session_key => '_portal_session',
   :secret      => '72bf006c18d459acf51836d2aea01e0afd0388f860fe4b07a9a57dedd25c631749ba9b65083a85af38bd539cc810e81f559e76d6426c5e77b6064f42e14f7415'
   }
   ...
   end

Do the same in AppB. (remember to use the very same secret)

Now you have shared sessions. Let's say you use restfull_authentication, wich sets a session variable called user_id. When you authenticate in appA it sets the user_id in the session. Now, in appB you just have to verify if user_id exists in the session.

This is the overall schema, you can elaborate more using this idea.

Upvotes: 0

Tom Harrison
Tom Harrison

Reputation: 14018

You should be OK as long as you own example.com and define your cookie domain correctly. There's a really good answer to how cookies work (or, as the author says, how browsers actually implement them) here: How do browser cookie domains work?

In rails, just pass the proper value for :domain when setting the cookie.

Upvotes: 0

Related Questions