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

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

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

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


当前回答

是的,从domain1获得cookie是完全可能的。domain2.example示例。我的社交网络的社交插件也遇到了同样的问题,经过一天的研究,我找到了解决方案。

首先,在服务器端,你需要有以下头文件:

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]

第二,在客户端:

在AJAX请求中,需要包含2个参数

crossDomain: true
xhrFields: { withCredentials: true }

例子:

type: "get",
url: link,
crossDomain: true,
dataType: 'json',
xhrFields: {
  withCredentials: true
}

其他回答

您不能跨域共享cookie。但是,您可以允许所有子域具有访问权限。若要允许example.com的所有子域具有访问权限,请将域设置为.example.com。

这是不可能的。例如访问example.com的cookie。

您可以尝试使用图像标记将cookie val推到另一个域。

在尝试这样做时,您的情况可能会有所不同,因为一些浏览器要求您在WebApp2域上有适当的P3P策略,否则浏览器将拒绝cookie。

如果你看plus.google.com p3p政策,你会看到他们的政策是:

CP="这不是P3P策略!更多信息请访问http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657。”

这就是他们对这些跨域请求使用的+1按钮的策略。

另一个警告是,如果您使用https,请确保图像标签指向https地址,否则cookie将不会设置。

function GetOrder(status, filter) {
    var isValid = true; //isValidGuid(customerId);
    if (isValid) {
        var refundhtmlstr = '';
        //varsURL = ApiPath + '/api/Orders/Customer/' + customerId + '?status=' + status + '&filter=' + filter;
        varsURL = ApiPath + '/api/Orders/Customer?status=' + status + '&filter=' + filter;
        $.ajax({
            type: "GET",
            //url: ApiPath + '/api/Orders/Customer/' + customerId + '?status=' + status + '&filter=' + filter,
            url: ApiPath + '/api/Orders/Customer?status=' + status + '&filter=' + filter,
            dataType: "json",
            crossDomain: true,
            xhrFields: {
                withCredentials: true
            },
            success: function (data) {
                var htmlStr = '';
                if (data == null || data.Count === 0) {
                    htmlStr = '<div class="card"><div class="card-header">Bu kriterlere uygun sipariş bulunamadı.</div></div>';
                }
                else {
                    $('#ReturnPolicyBtnUrl').attr('href', data.ReturnPolicyBtnUrl);
                    var groupedData = data.OrderDto.sort(function (x, y) {
                        return new Date(y.OrderDate) - new Date(x.OrderDate);
                    });
                    groupedData = _.groupBy(data.OrderDto, function (d) { return toMonthStr(d.OrderDate) });
                    localStorage['orderData'] = JSON.stringify(data.OrderDto);

                    $.each(groupedData, function (key, val) {

                        var sortedData = groupedData[key].sort(function (x, y) {
                            return new Date(y.OrderDate) - new Date(x.OrderDate);
                        });
                        htmlStr += '<div class="card-header">' + key + '</div>';
                        $.each(sortedData, function (keyitem, valitem) {
                            //Date Convertions
                            if (valitem.StatusDesc != null) {
                                valitem.StatusDesc = valitem.StatusDesc;
                            }

                            var date = valitem.OrderDate;
                            date = date.substring(0, 10).split('-');
                            date = date[2] + '.' + date[1] + '.' + date[0];
                            htmlStr += '<div class="col-lg-12 col-md-12 col-xs-12 col-sm-12 card-item clearfix ">' +
                        //'<div class="card-item-head"><span class="order-head">Sipariş No: <a href="ViewOrderDetails.html?CustomerId=' + customerId + '&OrderNo=' + valitem.OrderNumber + '" >' + valitem.OrderNumber + '</a></span><span class="order-date">' + date + '</span></div>' +
                        '<div class="card-item-head"><span class="order-head">Sipariş No: <a href="ViewOrderDetails.html?OrderNo=' + valitem.OrderNumber + '" >' + valitem.OrderNumber + '</a></span><span class="order-date">' + date + '</span></div>' +
                        '<div class="card-item-head-desc">' + valitem.StatusDesc + '</div>' +
                        '<div class="card-item-body">' +
                            '<div class="slider responsive">';
                            var i = 0;
                            $.each(valitem.ItemList, function (keylineitem, vallineitem) {
                                var imageUrl = vallineitem.ProductImageUrl.replace('{size}', 200);
                                htmlStr += '<div><img src="' + imageUrl + '" alt="' + vallineitem.ProductName + '"><span class="img-desc">' + ProductNameStr(vallineitem.ProductName) + '</span></div>';
                                i++;
                            });
                            htmlStr += '</div>' +
                        '</div>' +
                    '</div>';
                        });
                    });

                    $.each(data.OrderDto, function (key, value) {
                        if (value.IsSAPMigrationflag === true) {
                            refundhtmlstr = '<div class="notify-reason"><span class="note"><B>Notification : </B> Geçmiş siparişleriniz yükleniyor.  Lütfen kısa bir süre sonra tekrar kontrol ediniz. Teşekkürler. </span></div>';
                        }
                    });
                }
                $('#orders').html(htmlStr);
                $("#notification").html(refundhtmlstr);
                ApplySlide();
            },
            error: function () {
                console.log("System Failure");
            }
        });
    }
}

. config

包括UI原点和设置允许凭据为真

<httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="http://burada.com" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
        <add name="Access-Control-Allow-Credentials" value="true" />
      </customHeaders>
    </httpProtocol>

基于浏览器的存储主要有三种:

会话存储 本地存储 cookie存储


安全cookie -用于加密网站,以提供保护,免受来自黑客的任何可能威胁。 访问cookie - document.cookie。这意味着这个cookie是公开的,可以通过跨站点脚本来利用。保存的cookie值可以通过浏览器控制台看到。

作为预防措施,您应该总是尝试使用JavaScript使您的cookie在客户端不可访问。

HTTPonly - ensures that a cookie is not accessible using the JavaScript code. This is the most crucial form of protection against cross-scripting attacks. A secure attribute - ensures that the browser will reject cookies unless the connection happens over HTTPS. sameSite attribute improves cookie security and avoids privacy leaks. sameSite=Lax - It is set to Lax (sameSite = Lax) meaning a cookie is only set when the domain in the URL of the browser matches the domain of the cookie, thus eliminating third party’s domains. This will restrict cross-site sharing even between different domains that the same publisher owns. we need to include SameSite=None to avoid the new default of Lax:

注意:有一个规范草案要求当SameSite属性被设置为“none”时Secure属性被设置为true。一些web浏览器或其他客户端可能采用此规范。

使用include作为{withCredentials: true}必须包含来自前端的请求的所有cookie。

const data = { email: 'youremailaddress@gmail.com' , password: '1234' };
const response = await axios.post('www.yourapi.com/login', data , { withCredentials: true });

Cookie只能在安全的HTTPS连接上被接受。为了使其工作,我们必须将web应用程序移动到HTTPS。

在express.js

res.cookie('token', token, {
      maxAge: 1000 * 60 * 60 * 24, // would expire after (for 15 minutes  1000 * 60 * 15 ) 15 minutes
      httpOnly: true, // The cookie only accessible by the web server
      sameSite: 'none',
      secure: true, // Marks the cookie to be used with HTTPS only.
    });

参考文献1,参考文献2

除了@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=/;