跨域 Cookie [英] Cross-Domain Cookies
问题描述
我在两个不同的域中有两个 web 应用程序 WebApp1 和 WebApp2.
I have two webapps WebApp1 and WebApp2 in two different domains.
- 我正在 HttpResponse 中的 WebApp1 中设置 cookie.
- 如何从 WebApp2 中的 HttpRequest 读取相同的 cookie?
我知道这听起来很奇怪,因为 cookie 特定于给定的域,我们无法从不同的域访问它们;然而,我听说过可以跨多个 web 应用程序共享的跨域 cookie.如何使用跨域 cookie 实现此要求?
I know it sounds weird because cookies are specific to a given domain, and we can't access them from different domains; I've however heard of CROSS-DOMAIN cookies which can be shared across multiple webapps. How to implement this requirement using CROSS-DOMAIN cookies?
注意:我正在尝试使用 J2EE webapps
Note: I am trying this with J2EE webapps
推荐答案
是的,完全可以通过 domain2.com 从 domain1.com 获取 cookie.我的社交网络的社交插件遇到了同样的问题,经过一天的研究,我找到了解决方案.
Yes, it is absolutely possible to get the cookie from domain1.com by domain2.com. I had the same problem for a social plugin of my social network, and after a day of research I found the solution.
首先,在服务器端,您需要具有以下标头:
First, on the server side you need to have the following headers:
header("Access-Control-Allow-Origin: http://origin.domain:port");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST");
header("Access-Control-Allow-Headers: Content-Type, *");
在 PHP 文件中,您可以使用 $_COOKIE[name]
Within the PHP-file you can use $_COOKIE[name]
其次,在客户端:
在你的ajax请求中你需要包含2个参数
Within your ajax request you need to include 2 parameters
crossDomain: true
xhrFields: { withCredentials: true }
示例:
type: "get",
url: link,
crossDomain: true,
dataType: 'json',
xhrFields: {
withCredentials: true
}
这篇关于跨域 Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!