Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session across domains in Rails 4

I have an issue with wanting to use session across domains (not subdomain). Eg, I have .co.uk, .com.au, and .com all for the same address.

I know for subdomains I can use something like:

SomeApp::Application.config.session_store :cookie_store, key: '_some_app_session', domain => :all, :tld_length => 2

But I would like my solution to work between actually domains to have one set of sessions/cookies.

like image 934
res Avatar asked Mar 19 '15 12:03

res


2 Answers

As your default session store is 'cookie_store'

You could just do it the same way as when you might send an email link with an authentication token. Check to verify that the cookie is correct on example.org and, if it is, redirect them to:

http://example.com?token= and then check to make sure the token matches the one you have in the DB when they arrive. If the token does match, create the session cookie for the example.com domain and then change the token in the database.

This will successfully transfer from one domain to another while providing persistent login on the new domain (via cookie) and shutting the door behind them by changing the authentication token in the DB.

EDIT

To answer your question below, I don't think you need middleware or anything fancy. You could do a simple before filter in the application controller of example.org, something like:

before_filter :redirect_to_dot_com
...
def redirect_to_dot_com
  url = "http://example.com" + request.fullpath
  url= destination + (url.include?('?') ? '&' : '?') + "token=#{current_user.token}" if signed_in?
  redirect_to url, status: 301
end

That will redirect the user either way, and append the token to the query if the user is signed in on the .org site.

Go to more details on Persisting user sessions when switching to a new domain name (Ruby on Rails)

like image 114
user3118220 Avatar answered Oct 22 '22 23:10

user3118220


I wouldn't use the PHP style routings which pass ?php=bad style variables via :get especially if you're already using sessions. And also since then you'd have to parse the original URL and a bunch of other work.

Instead of using session[:edition_id] = 'UK' you can use:

cookies[:edition_id] = { value: 'UK', domain: 'some-app.com', expires: 1.year.from_now } 

# or if you want to be google 10.years.from_now

When you use session[:edition_id] = 'UK' the value will be encrypted by rails and stored in the _myapp_session cookie. But in your case that probably doesn't matter much.

If you set the cookie explicitly on the domain you want to read it from, it will work without having to set odd ball variables via get and then trying to interpret them again on redirect.

like image 2
holden Avatar answered Oct 22 '22 21:10

holden