Share a login cookie/session between domains in Ra

2019-09-16 08:46发布

To be totally clear, I definitely mean share sessions between domains, not just subdomains.

Anyway, imagine Tumblr where you can access a blog by going to <name>.tumblr.com, but you can also set it up to use a custom domain.

We're trying to do something similar. You can access your part of our site as normal, or you can set it up so that you can use a custom domain to visit your part of the site.

The important part here is that no matter what domain is used, it's all handled by the same box. This isn't SSO per se, since we are accessing the same Rails app, just from different domains.


Anyway, the question: What is the best way to make it so that if a user is logged in to our main site, they don't have to log in again when visiting our site via a custom domain.

Essentially, we want to make it so that a user signs in once and they remain signed in regardless of what domain they used to access our site.

Any advice is appreciated!

1条回答
Juvenile、少年°
2楼-- · 2019-09-16 09:14

You can store session in iframe on your main domain and access it by postMessage.

You can load iframe contains something like:

parent.postMessage(JSON.stringify({user_id: <%=@user.id %>, token: <%=@token %>, etc...}), '<%= @target_origin || '*'%>');

and event listener on page with this iframe process this message:

var listener = function (e) {
  if (e.origin === correctIframeTarget) {
    var data = JSON.parse(e.data);
    // etc...
};

if (window.addEventListener) {
  window.addEventListener('message', listener);
} else {
  window.attachEvent('onmessage', listener);
}

Notice: event listener should be added before iframe loading.

查看更多
登录 后发表回答