Keeping the cookie after a cross-domain ajax request

匿名 (未验证) 提交于 2019-12-03 03:04:01

问题:

A javascript application running on 10.0.0.1 tries to authenticate it's users with cross-domain ajax calls.

The request looks like:

function test(again){   $.ajax({     type: 'GET',     url: 'http://example.com/userinfo',     dataType: 'json',     success: function(userinfo){       if(again)         test(false);}});} test(true); 

The first response from the server tries to set a cookie:

Access-control-allow-origin:http://10.0.0.1 Set-Cookie:PHPSESSID=uuj599r4k1ohp48f1poobil665; expires=Sat, 28-Jan-2012 17:10:40 GMT; path=/ 

But the second request does not include this cookie, nor do any other ajax requests to that domain.

I am not trying to read the cookie for another domain, I just want the application on the other domain to be able to set and read its own cookie.

Is this possible?

I have tested in Chrome and Firefox 9.

回答1:

server should set header:

response.Headers.Add("Access-Control-Allow-Credentials", "true"); 

client set to:

xhrFields: {   withCredentials: true } 


回答2:

As long as you are using a browser which supports CORS, cookies on the AJAX request should work. But you must set withCredentials on the XMLHttpRequest to true.

See: The withCredentials attribute

I don't use JQuery but here's a question that deals specifically with setting withCredentials via JQuery.

Sending credentials with cross-domain posts?



回答3:

No, cookies cannot be shared cross domain. The same origin policy could be circumvented for AJAX calls using the Access-Control-* headers assuming the browser supports them, but for cookies there's no way.



回答4:

+Darin Dimitrov suspects that "the cookie is not saved by the browser because it comes from another domain than the one hosting the page which is at the origin of this call".

However, the cookie gets set as desired when using JSONP, but JSONP is only for GET requests.

My solution is to retrieve the cookie (a PHP session id) by loading the following php file in a <script>:

<? echo $_GET['callback'] . '("' . session_id() . '")'; ?> 

And to pass the session id as a request variable in all cross-domain POST requests.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!