The browser is failing to send cookies across different origins and domains even with CORS activated

I have set up a .net core webapi project to allow cross-origin requests by adding the necessary configurations in ConfigureServices and Configure methods. However, when trying to send a fetch request from the browser to the API, the cookies are not being sent along with the request. I have explored various solutions including disabling third-party cookies, but none seem to work.

The values controller in the project has a GET method that should return the cookies associated with the request. Despite setting up CORS and allowing credentials, the cookies are still not being passed to the API endpoint.

After extensive troubleshooting, it was discovered that even cookies from sub-a.domain.com were not transferred to sub-b.domain.com. As a workaround, we created a cookie bound to domain.com, which is successfully transmitted to both sub-a.domain.com and sub-b.domain.com. This solution effectively deals with the issue of sending cookies across different sub-domains within the same domain.

Answer №1

CORS serves the purpose of allowing the browser to utilize responses from cross-origin requests, but it does not facilitate the transfer of cookies across domains. The specification outlines the criteria for attaching a cookie to a request without any mention of CORS.

If cookies were permitted to accompany cross-origin requests, it would pose a significant security risk by enabling foreign domains to access sensitive data like user session tokens from your domain. A malicious developer could design an API that offers a helpful service and then gather numerous session tokens from websites utilizing the API (the originating sites can be easily identified via the Referer header).

The behavior observed with localhost and varying ports is expected because ports do not affect cookies, which is due to "historical reasons" (see: Are HTTP cookies port specific?)

Therefore, the available options include:

  • Configure the cookie domain to a higher-level domain
  • If feasible for your server, rely on headers instead of cookies; consider alternatives such as using localStorage with JavaScript and HTTP headers
  • If you have control over the infrastructure, employ a single domain for both UI and API and perform URL rewriting on the server side (e.g., directing incoming requests starting with /api/... to the local API URL and others to the local UI URL)

Answer №2

Issue with browser not sending cookies across origin domains when CORS is enabled.

Each cookie is associated with a specific domain, so you can set *.abc.com to work on abc.com and all its subdomains. Make sure your cookies are configured for *.abc.com like this: options.Cookie.Domain = ".contoso.com";

For more information, check out this link: how to share cookies

services.AddCors(options =>
        {
            options.AddPolicy(MyAllowSpecificOrigins,
            builder =>
            {
                builder.WithOrigins("http://example.com","*.example.com"
                                    "http://www.contoso.com");
            });
        });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fetching elements using Python Selenium with JavaScript

I am attempting to retrieve lists in Python Selenium using JavaScript as shown below lists = browser.execute_script("document.getElementById('permalink-overlay').getElementsByClassName('u-dir')") However, I am receiving an error in th ...

Selenium Chrome Driver: Troubleshooting a JavaScript onClick event - element remains hidden or fails to trigger action

Currently, I'm facing an issue with a script I wrote at work to automate VMWare's Airwatch token generation for MDM. The script was working fine until the server/Airwatch Console was updated and it caused this javascript onclick function to break ...

How to selectively import specific modules in three.js using ES6 syntax

I recently integrated the three.js library using NPM with the goal of leveraging its new ES6 modular architecture. This design allows for selective importation of specific modules as outlined in this resource: Threejs - Import via modules. For bundling an ...

What is the best way to send an array of numbers by utilizing e.target.value and React useState Hooks?

Trying to update the numbers array by passing it into submitNumbers() and using an onChange event. Issue arises when trying to use useState() to handle the array. When attempting to log these constants while the code is running, they are returning as not ...

What is the best way to switch to the next track and pause the current track in dynamic content using JavaScript?

Is there a way to use javascript to play the next song and pause the currently playing song, especially when dealing with dynamic content that shares the same id and onClick value? How can we effectively manage dynamic content in javascript? https://i.sst ...

TypeOrm is struggling to identify the entities based on the directory path provided

Currently, I am utilizing TypeORM with NestJS and PostgreSql to load entities via the datasource options object. This object is passed in the useFactory async function within the TypeORM module as shown below: @Module({ imports: [TypeOrmModule.forRootAsy ...

When utilizing the RTK Query custom hook in Typescript, an error may occur stating "Invalid hook call. Hooks can only be called inside the body of a

While delving into next.js with rtkquery and typescript, I encountered an error in the useEffect hook within GoogleMapComponent.tsx. The React site pointed out that I was violating some rules of hooks usage, but this is a functional component being used in ...

How can we effectively pass configuration settings and parameters to a class library module?

As I develop a class library for widespread client use, my goal is to make it configurable. For instance, I hope to allow clients to specify the path for temporary files used by the library. I am contemplating the best approach for achieving this goal. Sh ...

Is it possible for Typescript to resolve a json file?

Is it possible to import a JSON file without specifying the extension in typescript? For instance, if I have a file named file.json, and this is my TypeScript code: import jsonData from './file'. However, I am encountering an error: [ts] Cannot ...

Place an overlay element in the top-left corner of a perfectly centered image

Currently, there is an image that is centered on the screen using flexbox: .center-flex { display: flex; justify-content: center; } <div class="center-flex"> <img id="revealImage"> </div> An attempt is be ...

Developing a MySQL DB-driven Node.js dashboard without the need for a poller

After exploring various StackOverflow posts on the topic, I haven't been able to find a solution that fits my specific situation. We have multiple monitoring instances across our network, each monitoring different environments (such as Nagios, Icinga ...

A step-by-step guide on incorporating box-shadow for the jackColor in the Switchery Plugin

I am looking to add a box shadow to my iOS7 style switches for checkboxes when they are checked. Here is the code I have so far: var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch')); elems.forEach(function (html) { va ...

Increased Z-index on an unfamiliar site

I'm in the process of enhancing the Moodle platform at my school with a userscript, and I want to create a sleek UI for it. One feature I want to add is a progress bar that stays fixed at the top of the browser viewport so that it remains visible as ...

Retrieving JavaScript return values in a C# WebBrowser control within a WPF application

I utilized JavaScript injection into WebBrowser control in C# (System.Windows.Controls.WebBrowser) to achieve, <C#> IHTMLDocument2 webdoc = (IHTMLDocument2)webBrowser1.Document; string var = File.ReadAllText("C:/.../Resources/script.txt"); object re ...

Adapting website content in real-time based on the information stored in a MySQL

Looking to update my website dynamically based on a value from the MySQL database in real-time. I currently have some code that partially achieves this functionality, but it seems to fail after a few calls by randomly switching between two values. I have ...

How can I retrieve the element that the user is currently typing in within a designMode iframe?

I have a situation where I have an iframe that allows users to type and edit various divs within it. However, there is one specific div that should not be editable by the user. I have tried to prevent users from clicking on the div using JavaScript: docum ...

The functionality of the Express module in a Node.js environment is not functioning as

I am currently utilizing the 'express' module within Node JS following the example here Upon attempting to run the server and accessing 'localhost:8000', I encounter the following error: Error: No default engine was specified and no e ...

Can't get window.focus to work in JavaScript, but window.close is working fine

Goal: Notify the User before exiting the parent page if they have a Web Based Training Pop-up open. If they choose to stay on the page by clicking cancel, I want the focus to return to the pop-up. Currently, it remains minimized which is causing an issue. ...

Loading external libraries in Angular2: A step-by-step guide

I'm currently working on incorporating a Datepicker in Angular 2, but I'm facing an issue where the library is not loading. This is causing a template parsing error stating 'material-datepicker' is not a recognized element: My System.c ...

Concealing a Div on Click Outside of Child Div in ReactJS

I have a parent div with a child div in the center. I am trying to figure out how to close the parent div only when clicking outside of the child div. My current code is structured like this, using triggerParentUpdate to control whether the div should be d ...