Nguyen Ruby
Nguyen Ruby

Reputation: 221

Share session between some subdomains in Rails?

Is it possible share session for some special subdomain? For example I've some subdomain:

and dynamic subdomain with regex: user.*.example.com (user.sub1.example.com)

when user login through user.example.com => auto login on user.*.example.com but not login to admin.example.com

How Can I do this?

Upvotes: 4

Views: 2270

Answers (2)

Amit Patel
Amit Patel

Reputation: 15985

Checkout the solution at https://www.botreetechnologies.com/blog/how-to-share-session-between-rails-4-applications

The blog talks about Rails 4 but that solution is applicable to not only any version of Rails but for any Rack application

Upvotes: -1

Hammad Maqbool
Hammad Maqbool

Reputation: 59

Add this in your /config/initilizers/session_store.rb file:

AppName::Application.config.session_store :cookie_store, key: '_application_devise_session', domain: :all

'domain: all' creates a cookie for all the different subdomains that are visited during that session (and it ensures that they are passed around between request). If no domain argument is passed, it means that a new cookie is created for every different domain that is visited in the same session and the old one gets discarded.

Ultimately the tld_length (top level domain length) in that expression. The default tld_length is 1 while manager.example.come has a tld_length of 2 and 127.0.0.1.example.com has a tld_length of 5, for example. So what I had in the session_store.rb file for subdomains on example.com in development and whatever else in production was the below.

AppName::Application.config.session_store :cookie_store, key: '_application_devise_session', domain: :all, tld_length: 2

To configure per environment you could use the following:

Rails.application.config.session_store :cookie_store, key: '_my_app_session', domain: {
  production: '.example.com',
  development: '.example.dev'
}.fetch(Rails.env.to_sym, :all)

Source: https://github.com/plataformatec/devise/wiki/How-To:-Use-subdomains

Upvotes: 4

Related Questions