Hi i have a multitenant rails 4 application that has a simple sign in solution. However each user has a subdomain that the user gets redirected to after login.
The problem is that as they arrive at the subdomain they are not logged in anymore due to the known problem that sessions are not shared across subdomains.
I have tried several different solution to this problem, however i do not get the session to persist across subdomains. I believe this might be due to my development environment?
I have tried all answers to this question: Share session (cookies) between subdomains in Rails?
Nothing seems to work. Is there something I'm missing here? Is it the browser or rails 4 or....? How should i approach this problem?
Edit: My sessions_store initializer:
Imagesite::Application.config.session_store :cookie_store, key: '_imagesite_session', :domain => "imagesite.dev"
I have also tried ".imagesite.dev"
and :all
.
I also tried the solution described by Evan at the other question linked above.
Examples of subdomains: "ole.imagesite.dev" or "ole2.imagesite.dev" just basic subdomain based on what the user has entered as his/her subdomain.
I finally solved it!
I had to set the domain when i create the auth_token cookie. like this:
cookies[:auth_token] = { value: user.auth_token, domain: ".lvh.me" }
and like this to delete the cookie:
cookies.delete(:auth_token, :domain => '.lvh.me')
Complete example:
def create
user = User.find_by_username(params[:username])
user ||= User.find_by_email(params[:username])
if user && user.authenticate(params[:password])
# session[:user_id] = user.id
if params[:remember_me]
cookies.permanent[:auth_token] = { value: user.auth_token, domain: ".lvh.me" }
else
cookies[:auth_token] = { value: user.auth_token, domain: ".lvh.me" }
end
redirect_to root_url(:subdomain => "#{current_user.subdomain}"), notice: "You are now loged in."
else
flash.now.alert = "Email or password is invalid"
render "new"
end
end
def destroy
#session[:user_id] = nil
cookies.delete(:auth_token, :domain => '.lvh.me')
redirect_to root_url(:subdomain => false), notice: "Loged out"
end
With Rails 4.2.5.1, the following works for me:
Rails.application.config.session_store :cookie_store, key: '_magic_session', tld_length: 2
Yes, without the domain: option.
Update: It's better to set the domain:
option to :all
.
Rails.application.config.session_store :cookie_store, key: '_magic_session', domain: :all, tld_length: 2
It may has to be domain: "magic.com"
if env["HTTP_HOST"]
holds an IP address, not a domain name, in the development environment or behind a proxy. For nginx, proxy_set_header HOST $host:$server_port;
can preserve the domain name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With