Cross-Domain Cookies

CookiesWeb ApplicationsCross Domain

Cookies Problem Overview

I have two webapps WebApp1 and WebApp2 in two different domains.

  1. I am setting a cookie in WebApp1 in the HttpResponse.
  2. How to read the same cookie from HttpRequest in WebApp2?

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?

Note: I am trying this with J2EE webapps

Cookies Solutions

Solution 1 - Cookies

Yes, it is absolutely possible to get the cookie from by 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, *");

Within the PHP-file you can use $_COOKIE[name]

Second, on the client side:

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

Solution 2 - Cookies

As other people say, you cannot share cookies, but you could do something like this:

  1. centralize all cookies in a single domain, let's say
  2. when the user makes a request to you redirect him to
  3. redirects him back to with the information you need

Of course, it's not completely secure, and you have to create some kind of internal protocol between your apps to do that.

Lastly, it would be very annoying for the user if you do something like that in every request, but not if it's just the first.

But I think there is no other way...

Solution 3 - Cookies

As far as I know, cookies are limited by the "same origin" policy. However, with CORS you can receive and use the "Server B" cookies to establish a persistent session from "Server A" on "Server B".

Although, this requires some headers on "Server B":

Access-Control-Allow-Credentials: true

And you will need to send the flag "withCredentials" on all the "Server A" requests (ex: xhr.withCredentials = true;)

You can read about it here:

Solution 4 - Cookies

There's no such thing as cross domain cookies. You could share a cookie between and but never between and and that's for security reasons.

Solution 5 - Cookies

The smartest solution is to follow facebook's path on this. How does facebook know who you are when you visit any domain? It's actually very simple:

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.

So when you see a like button on, you are actually visiting a Facebook page at the same time. That allows Facebook to read a cookie on your computer, which it has created the last time you’ve logged in to Facebook.

A fundamental security rule in every browser is that only the website that has created a cookie can read it later on. And that is the advantage of the iframe: it allows Facebook to read your Facebook-cookie even when you are visiting a different website. That’s how they recognize you on and display your friends there.


Solution 6 - Cookies

Cross-domain cookies are not allowed (i.e. site A cannot set a cookie on site B).

But once a cookie is set by site A, you can send that cookie even in requests from site B to site A (i.e. cross-domain requests): > XMLHttpRequest from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request. The third-party cookies obtained by setting withCredentials to true will still honor same-origin policy and hence can not be accessed by the requesting script through document.cookie or from response headers.

Make sure to do these things:

  1. 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 to 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
  2. 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.
  3. In general:
    • Your browser hasn't disabled 3rd-party cookies. (* see below)

Things that you don't need (just use the above):

  1. domain attribute in the Set-Cookie; you can choose a root domain (i.e. can set a cookie with a domain value of, but it's not necessary; the cookie will still be sent to, even if sent from
  2. 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)

Let's clarify a "domain" vs a "site"; a quick reminder of "anatomy of a URL" helps me. In this URL, remember these main parts (got from this paper):

  • the "protocol": https://
  • the "hostname/host":
  • the "port": 8888
  • the "path":/examples/index.html.

Notice the difference between "path" and "site" for Cookie purposes. "path" is not security-related; "site" is security-related:


Servers can set a Path attribute in the Set-Cookie, but it doesn't seem security related: > Note that path was intended for performance, not security. Web pages having the same origin still can access cookie via document.cookie even though the paths are mismatched.


The SameSite attribute, according to article, can restrict or allow cross-site cookies; but what is a "site"? > It's helpful to understand exactly what 'site' means here. The site is the combination of the domain suffix and the part of the domain just before it. For example, the domain is part of the site...

This means a request to from , is a sameSite request.

> The public suffix list defines this, so > it's not just top-level domains like .com but also includes services > like

This means a request to from , is a a cross-site request.

This means what's to the left of the public suffix; is the subdomain (but the subdomain is a part of the host; see the BONUS reply in this answer)

  • www is the subdomain in; same site as
  • your-project is the domain in; separate site as

In this URL, remember these parts:

  • the "protocol": https://
  • the "hostname" aka "host":
  • (in cases like "", the entire "" is also a hostname)
  • the "port": 8888
  • the "site":
  • the "domain":
  • the "subdomain": www
  • the "path": /examples/index.html

Useful links:

(Be careful; I was testing my feature in Chrome Incognito tab; according to my chrome://settings/cookies; my settings were "Block third party cookies in Incognito", so I can't test Cross-site cookies in Incognito.)

a browser is open to the URL chrome://settings/cookies, which shows that

Solution 7 - Cookies

You cannot share cookies across domains. You can however allow all subdomains to have access. To allow all subdomains of to have access, set the domain to

It's not possible giving access to's cookies though.

Solution 8 - Cookies

Do what Google is doing. Create a PHP file that sets the cookie on all 3 domains. Then on the domain where the theme is going to set, create a HTML file that would load the PHP file that sets cookie on the other 2 domains. Example:

      <p>Please wait.....</p>
      <img src="" />
      <img src="" />

Then add an onload callback on body tag. The document will only load when the images completely load that is when cookies are set on the other 2 domains. Onload Callback :

   function loadComplete(){
      window.location="";//URL of domain1
<body onload="loadComplete()">


We set the cookies on the other domains using a PHP file like this :

   setcookie("theme", $_GET['theme'], time()+3600);

Now cookies are set on the three domains.

Solution 9 - Cookies

You can attempt to push the cookie val to another domain using an image tag.

http://WebApp2/keepalive.aspx?val=crcuevfbjrbbgggdaocyeejkewgpjbjeeqinoemd" class="traffic" alt="" />

Your mileage may vary when trying to do this because some browsers require you to have a proper P3P Policy on the WebApp2 domain or the browser will reject the cookie.

If you look at p3p policy you will see that their policy is:

CP="This is not a P3P policy! See for more info."

that is the policy they use for their +1 buttons to these cross domain requests.

Another warning is that if you are on https make sure that the image tag is pointing to an https address also otherwise the cookies will not set.

Solution 10 - Cookies

There's a decent overview of how Facebook does it here on

There's also Browser Fingerprinting, which is not the same as a cookie, but serves a like purpose in that it helps you identify a user with a fair degree of certainty. There's a post here on Stack Overflow that references upon one method of fingerprinting

Solution 11 - Cookies

One can use invisible iframes to get the cookies. Let's say there are two domains, and For the index.html of domain one can add (notice height=0 width=0):

<iframe height="0" id="iframe" src="" width="0"></iframe>

That way your website will get cookies assuming that sets the cookies.

The next thing would be manipulating the site inside the iframe through JavaScript. The operations inside iframe may become a challenge if one doesn't own the second domain. But in case of having access to both domains referring the right web page at the src of iframe should give the cookies one would like to get.

Solution 12 - Cookies

I've created an NPM module, which allows you to share locally-stored data across domains:

By using an iframe hosted on Domain A, you can store all of your user data on Domain A, and reference that data by posting requests to the Domain A iframe.

Thus, Domains B, C, etc. can inject the iframe and post requests to it to store and access the desired data. Domain A becomes the hub for all shared data.

With a domain whitelist inside of Domain A, you can ensure only your dependent sites can access the data on Domain A.

The trick is to have the code inside of the iframe on Domain A which is able to recognize which data is being requested. The README in the above NPM module goes more in depth into the procedure.

Hope this helps!

Solution 13 - Cookies

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;
            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>';
                            htmlStr += '</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>';
            error: function () {
                console.log("System Failure");


Include UI origin and set Allow Credentials to true

        <add name="Access-Control-Allow-Origin" value="" />
        <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" />

Solution 14 - Cookies

Along with @Ludovic(approved answer) answers we need to check one more option when getting set-cookies header,

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

Check for Path attribute value also. This should be the same as your API starting context path like below

or use below value when not sure about context path


Solution 15 - Cookies

Since it is difficult to do 3rd party cookies and also some browsers won't allow that.

You can try storing them in HTML5 local storage and then sending them with every request from your front end app.

Solution 16 - Cookies

Read Cookie in Web Api

var cookie = actionContext.Request.Headers.GetCookies("newhbsslv1");

                    Logger.Log("Cookie  " + cookie, LoggerLevel.Info);
                    Logger.Log("Cookie count  " + cookie.Count, LoggerLevel.Info);
                    if (cookie != null && cookie.Count > 0)
                        Logger.Log("Befor For  " , LoggerLevel.Info);
                        foreach (var perCookie in cookie[0].Cookies)
                            Logger.Log("perCookie  " + perCookie, LoggerLevel.Info);

                            if (perCookie.Name == "newhbsslv1")
                                strToken = perCookie.Value;


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSundarJavaDeveloperView Question on Stackoverflow
Solution 1 - CookiesLudovicView Answer on Stackoverflow
Solution 2 - CookiesalcuadradoView Answer on Stackoverflow
Solution 3 - CookiesVitae AliquamView Answer on Stackoverflow
Solution 4 - CookiesDarin DimitrovView Answer on Stackoverflow
Solution 5 - CookiesMorteza Shahriari NiaView Answer on Stackoverflow
Solution 6 - CookiesThe Red PeaView Answer on Stackoverflow
Solution 7 - CookiesDaniel EgebergView Answer on Stackoverflow
Solution 8 - CookiesHossain KhademianView Answer on Stackoverflow
Solution 9 - CookiesBryan FochtView Answer on Stackoverflow
Solution 10 - CookiesbyZeroView Answer on Stackoverflow
Solution 11 - CookiesVadym TyemirovView Answer on Stackoverflow
Solution 12 - CookiesjmealyView Answer on Stackoverflow
Solution 13 - Cookiesuser7712621View Answer on Stackoverflow
Solution 14 - Cookiessharad jainView Answer on Stackoverflow
Solution 15 - CookiesBaraja SwargiaryView Answer on Stackoverflow
Solution 16 - Cookiesuser7712621View Answer on Stackoverflow