我有两个WebApp1和WebApp2在两个不同的域。

我在WebApp1的HttpResponse中设置了一个cookie。 如何从WebApp2中的HttpRequest读取相同的cookie ?

我知道这听起来很奇怪,因为cookie是特定于给定域的,我们不能从不同的域访问它们;不过我听说过跨域cookie,它可以在多个web应用程序之间共享。如何使用跨域cookie实现这一需求?

注意:我正在尝试使用J2EE web应用程序


当前回答

在nfriedly.com上有一个关于Facebook如何做到这一点的不错的概述

还有浏览器指纹识别,它与cookie不同,但作用类似,因为它可以帮助您以相当程度的确定性识别用户。Stack Overflow上有一篇文章提到了一种指纹识别方法

其他回答

最聪明的解决办法就是效仿facebook的做法。当你访问任何域名时,facebook如何知道你是谁?其实很简单:

The Like button actually allows Facebook to track all visitors of the external site, no matter if they click it or not. Facebook can do that because they use an iframe to display the button. An iframe is something like an embedded browser window within a page. The difference between using an iframe and a simple image for the button is that the iframe contains a complete web page – from Facebook. There is not much going on on this page, except for the button and the information about how many people have liked the current page.

所以当你在cnn.com上看到一个“喜欢”按钮时,你实际上是在同时访问一个Facebook页面。这使得Facebook可以读取你电脑上的cookie,这些cookie是它在你上次登录Facebook时创建的。

每种浏览器的一个基本安全规则是,只有创建了cookie的网站以后才能读取它。这就是iframe的优势:它允许Facebook读取你的Facebook-cookie,即使你在访问另一个网站。这就是他们如何在cnn.com上认出你,并在那里展示你的朋友。

来源:

http://dorianroy.com/blog/2010/04/how-facebooks-like-button-works/ https://stackoverflow.com/a/8256920/715483

你可以使用隐形的iframe来获取cookie。假设有两个定义域,a。example和b。example。对于a.example域的index.html,可以添加(注意height=0 width=0):

<iframe height="0" id="iframe" src="http://b.example" width="0"></iframe>

这样,您的网站将获得b.example cookie,假设http://b.example设置了cookie。

下一件事是通过JavaScript在iframe中操作站点。如果不拥有第二个域,iframe内部的操作可能会成为一个挑战。但是,如果能够访问这两个域,在iframe的src中引用正确的网页应该会给出一个想要获得的cookie。

除了@Ludovic(已批准的答案)的答案外,我们需要在获得set-cookies报头时检查另一个选项,

set-cookie: SESSIONID=60B2E91C53B976B444144063; Path=/dev/api/abc; HttpOnly

还要检查Path属性值。这应该与下面所示的API起始上下文路径相同

https://www.example.com/dev/api/abc/v1/users/123

或者在不确定上下文路径时使用下面的值

Path=/;

做谷歌正在做的事情。创建一个PHP文件,在所有3个域上设置cookie。然后在主题将要设置的域上,创建一个HTML文件,该文件将加载在其他2个域上设置cookie的PHP文件。例子:

<html>
   <head></head>
   <body>
      <p>Please wait.....</p>
      <img src="http://domain2.example/setcookie.php?theme=whateveryourthemehere" />
      <img src="http://domain3.example/setcookie.php?theme=whateveryourthemehere" />
   </body>
</html>

然后在body标签上添加一个onload回调。文档只会加载时,图像完全加载,即当cookie设置在其他2个域。Onload回调:

<head>
   <script>
   function loadComplete(){
      window.location="http://domain1.example";//URL of domain1
   }
   </script>
</head>
<body onload="loadComplete()">

setcookie.php

我们使用PHP文件在其他域上设置cookie,如下所示:

<?php
if(isset($_GET['theme'])){
   setcookie("theme", $_GET['theme'], time()+3600);
}
?>

现在在三个域中设置了cookie。

因为很难做第三方cookie,也有些浏览器不允许这样做。

你可以尝试将它们存储在HTML5本地存储中,然后将它们与前端应用程序的每个请求一起发送。