Persisting user sessions when switching to a new d

2019-05-29 19:03发布

My Rails app is currently available at example.org, but I want to switch to example.com

Doing a wildcard 301 redirect in routes.rb isn't a problem, but I would like to persist the user sessions as well. Since the new domain won't have access to the cookies of the old domain, what's the best (secure and as easy as possible) way to redirect the user to the new domain and still have him/her signed in?

I've found numerous of threads talking about setting up cross-domain web apps using complicated authentication tokens methods, but I'm looking for a one-time one-way migration so I'm hoping the solution will be simpler for this.

Any suggestions?

I'm using Ruby on Rails 3, OmniAuth, and using the default 'cookie_store' as my session store.

1条回答
We Are One
2楼-- · 2019-05-29 19:12

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=<their 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.

查看更多
登录 后发表回答