从一个Ajax请求设置上一个子一个cookie(Setting a cookie on a subd

2019-07-01 15:05发布

I have a webapp on www.example.com and an API on api.example.com.

The webapp makes ajax calls to the API.

Somewhere I need to put a cookie on api.example.com to keep sessions track.

To track my problem I've set test cookies on both subdomaines from the webapp and the api. The webapp set a cookie on .exemple.com and the api set one on .exemple.com and another on api.exemple.com. Cookies are set using Domain=.exemple.com only. No path, no HTTPOnly.

Note: In the end I need only one on api.exemple.com. But theses are for the tests.

Direct queries using my browser (Firefox 16) works fine. Query on api: the two cookies are set and sent. Query on www: the cookie is set and the two from the api is sent too. (Provided I query www after the api, of course).

Now, I clean the browser cookies and query www only. Query on www: works fine, same as before. Subquery on api, from www's ajax request: no cookies are sent. Set-Cookies does nothing. Using Firebug I see the cookies in the response. But no traces of them on subsequent requests or the page informations.

I event tried to enable the cookies log on Firefox. Absolutly no traces of the cookies from api, not even a reject notice.

In the end I only need a way to store one cookie on api. And for that, I quite open :)

Informations: The two servers are NodeJS. I've tried to set the cookie on the server side (Set-Cookie header), on the client side (document.cookies), manually using firebug.

Others posts I've checked with no solutions (And many others which I don't recall):

setting cross-subdomain cookie with javascript

Cookies and subdomains

Can subdomain.example.com set a cookie that can be read by example.com?

Answer 1:

将允许凭据API头

Access-Control-Allow-Credentials: true

使用withCredentials的请求

$.ajax({
    url: a_cross_domain_url,
    xhrFields: { 
        withCredentials: true 
    }
});

否则XMLHttpRequest不会发送的cookie,而不管的Access-Control-Allow-Credentials头。

卸下通配符Access-Control-Allow-Origin

Access-Control-Allow-Origin: http://www.example.com

通配符*将无法正常工作。 如果浏览器将丢弃该响应withCredentials设置。

参考文献:

http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/

https://developer.mozilla.org/en-US/docs/HTTP_access_control

http://arunranga.com/examples/access-control/credentialedRequest.html

http://api.jquery.com/jQuery.ajax/



文章来源: Setting a cookie on a subdomain from an ajax request