Gangmax Blog

Cross domain cookie, redirect and more

From here, here, and here.

Default

By default, the domain names which have the same second level domain can share the cookies. Like:

1
2
example.com & ab.example.com & de.example.com & xy.ab.example.com: YES
sun.com & emc.com: NO

P3P

By adding the “p3p” info in HTTP header, the cookie set by a website is able to be accessed by the other website.

JSONP

From here and here.

The following content is not about cross domain cookie, but about cross domain data access.

A seciruty assumption “same origin policy“ of a web browser when it’s executing Javascript code in it is that, if the current html page is loaded from website A, the Javascript code is being executed on this page can only access “DATA” from website A, not from any other websites. This restriction is aimed to forbid website A getting(stealing?) user’s “DATA” on website B. However, the “DATA” here does not include the “<script>” tag content. So “jsonp” leverages this character to workaround the “same origin policy” restriction.

With “jsonp”, Javascript code on a page loaded from website A can get data from website B by doing the following steps:

  • Define a callback function like below:
1
2
3
mycallback = function(data){
alert("data from website B: " + data);
};
1
mycallback({ foo: 'bar' });

By doing this, Javascript code on a page loaded from website A can get data from website B.

With JQuery, this is more easier:

Server side:

1
2
3
4
5
6
7
8
get '/jsonp' do
callback = params['callback']
content_type :js
content = { :response => 'Sent via JSONP',
:timestamp => Time.now,
:random => rand(10000) }
"#{callback}(#{content.to_json})"
end

Client side:

1
2
3
4
var url = host_prefix + '/jsonp?callback=?';
$.getJSON(url, function(jsonp){
$("#jsonp-response").html(JSON.stringify(jsonp, null, 2));
});

For the “taobao.com/tmall.com” case, they use the following solution to get user cookie data accross domains in “jsonp” way:

  1. Create a server side API(https://www.taobao.com/go/app/tmall/login-api.php?0.6783450077710154) to return your local cookies.

  2. When you access “tmall.com”, a Javascript snippet calls the API to create Javascript on the fly, and load it by using “jsonp“ way. Then the cookie info is available.

Go back to the “same origin policy“: if it allows to return “<script>” content, forbidding other data form transportation is unreasonable, since script is a form of data, and data can be part of script.

Comments