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

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

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

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


当前回答

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。但是,您可以允许所有子域具有访问权限。若要允许example.com的所有子域具有访问权限,请将域设置为.example.com。

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

就像其他人说的,你不能分享cookie,但你可以这样做:

将所有cookie集中到一个域中,例如cookemaker .example 当用户向example.com发出请求时,您将他重定向到cookiemaker.example cookiemaker。Example将他重定向到example.com,并提供你需要的信息

当然,它不是完全安全的,你必须在你的应用程序之间创建某种内部协议来做到这一点。

最后,如果在每个请求中都这样做,对用户来说会非常讨厌,但如果只是第一个请求就不会。

但我认为没有别的办法了。

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

会话存储 本地存储 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

不允许跨域cookie(即站点A不能在站点B上设置cookie)。

但是一旦站点a设置了cookie,您甚至可以在从站点B到站点a的请求中发送该cookie(即跨域请求):

来自不同域的XMLHttpRequest不能为自己的域设置cookie值,除非在发出请求之前将withCredentials设置为true。通过将withCredentials设置为true获得的第三方cookie仍然遵循同源策略,因此请求脚本无法通过文档访问。Cookie或响应头。

一定要做到以下几点:

When setting the cookie in a response The Set-Cookie response header includes SameSite=None if the requests are cross-site (note a request from www.example.dev to static.example.dev is actually a same-site request, and can use SameSite=Strict) The Set-Cookie response header should include the Secure attribute if served over HTTPS; as seen here and here When sending/receiving the cookie: The request is made with withCredentials: true, as mentioned in other answers here and here, including the original request whose response sets the cookie set in the first place For the fetch API, this attribute is credentials: 'include', vs withCredentials: true For jQuery's ajax method, note you may need to supply argument crossDomain: true The server response includes cross-origin headers like Access-Control-Allow-Origin, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, and Access-Control-Allow-Methods As @nabrown points out: "Note that the "Access-Control-Allow-Origin" cannot be the wildcard (*) value if you use the withCredentials: true" (see @nabrown's comment which explains one workaround for this. In general: Your browser hasn't disabled 3rd-party cookies. (* see below)

你不需要的东西(使用上面的):

domain attribute in the Set-Cookie; you can choose a root domain (i.e. a.example.com can set a cookie with a domain value of example.com, but it's not necessary; the cookie will still be sent to a.example.com, even if sent from b.other-site.example For the cookie to be visible in Chrome Dev Tools, "Application" tab; if the value of cookie HttpOnly attribute is true, Chrome won't show you the cookie value in the Application tab (it should show the cookie value when set in the initial request, and sent in subsequent responses where withCredentials: true)

注意Cookie中“路径”和“站点”之间的区别。“path”与安全无关;“site”与安全相关:

path

服务器可以在set - cookie中设置Path属性,但这似乎与安全无关:

注意,该路径用于性能,而不是安全性。具有相同来源的网页仍然可以通过文档访问cookie。Cookie,即使路径不匹配。

site

根据example.dev文章,SameSite属性可以限制或允许跨站点cookie;但是什么是“站点”呢?

准确理解“site”在这里的意思是很有帮助的。网站是域名后缀和域名前面的部分的组合。例如,www.example.dev域是example.dev站点的一部分…

这意味着从www.example.dev到static.example.dev的请求是一个sameSite请求(url的唯一区别在于子域)。

公共后缀列表定义了这个,所以 它不只是像。com这样的顶级域名,还包括服务 像github.io

这意味着对your-project.github的请求。IO来自my-project.github。io,是一个跨站点请求(这些url在不同的域,因为github。IO是域后缀;你的项目和我的项目的领域是不同的;因此不同的网站)

这意味着public后缀的左边;是子域(但子域是主机的一部分;请看这个答案中的奖金回复)

WWW是www.example.dev的子域;与static.example.dev相同的站点 Your-project是Your-project .github.io中的域;单独的网站my-project.github.io

在这个URL https://www.example.com:8888/examples/index.html中,请记住以下部分:

“协议”:https:// “方案”:HTTPS “端口”:8888 “域名”也就是位置。主机名:www.example.com “域名后缀”即“顶级域名”(TLD): com domain:示例 “子域”:WWW(子域可以是单层的(如WWW),也可以是多层的(如foo。Bar in foo.bar.example.com) “站点”(即“跨站点”,如果另一个URL具有不同的“站点”值):example.com "site" = "域名" + "域名后缀" = example.com 路径:/examples/index.html

有用的链接:

URL的剖析 同源cookie策略和URL剖析 SameSite cookies解释道 安全的跨域cookie的HTTP |互联网服务和应用期刊|全文 draft-ietf-httpbis-rfc6265bis-03 Web安全1:同源和Cookie策略 Set-Cookie - HTTP | MDN

(小心;我在Chrome隐身标签测试我的功能;根据我的chrome://设置/cookies;我的设置是“Incognito屏蔽第三方cookie”,所以我不能在Incognito中测试跨站点cookie。)

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

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