Reading cookies from server from another domain

2019-07-23 18:59发布

问题:

I have a UI in AngularJS making calls to REST webservice in Java. Both are deployed on different domains. The webservice and AngularJS both have CORS enabled.

The webservice returns a cookie as part of one REST request. The cookie has the webservice domain in it.

In my AngularJS app, I will be making that REST request to the server and then have to read that cookie returned as response.

How can I read the cookie returned back from that webservice? I have read that I cannot access the cookies which are from different domain. I have not exactly understood how does this actually work.

Another question is that if I cannot read the cookie, then can I set cookie from AngularJS app for that domain and that will be sent across to the webservice?

回答1:

You can't access cookies from another domain via JS, and may not be able to access them at all from JS depending on the properties of the cookie. This is all enforced by the browser.

If you are using an API hosted on another domain, then you might consider using tokens and local storage, and then using an HttpInterceptor to add the security token to your headers when making calls.

If your security infrastructure depends on you having cookies, then you are going to have to use some kind of shared token that can be exchanged for a cookie on both domains.