Search code examples
asp.net-mvcasp.net-core.net-corecookies

Error "Set-Cookie header was blocked because its domain attribute was invalid" on one domain, same controller


I'm building a Asp.net core 8 mvc application and have one Controller.

My goal is to set a persistent cookie on a 302 redirect before redirecting to a different domain. My Controller "Checker" Action "Check1" redirects first to Action "Check2" within the same Controller. "Check2" redirects at the end to a external url.

Check1 url: https://localhost:7058/checker/Check1    
Check2 url: https://localhost:7058/checker/Check2

Within the Developer Tools on Tab "Network" I see the two redirects.

The first redirect from "Check1" to "Check2" shows under "Response Headers" a warning "This attempt to set a cookie via a Set-Cookie header was blocked because its Domain attribute was invalid with regards to the current host url." and no cookie is set.

Code to set the cookie

Response.Cookies.Append("afc", token, new CookieOptions
                {
                    Domain = baseUrl,
                    IsEssential = true,
                    Expires = DateTime.Now.AddDays(365),
                    Secure = true,
                    SameSite = SameSiteMode.Lax,
                    Path = "/"
                });

baseUrl is set to "https://localhost:7058"

Set-Cookie:

afc=test123; expires=Thu, 10 Apr 2025 17:15:54 GMT; domain=https://localhost:7058; path=/; secure; samesite=lax

What have I checked?

  1. Application is using https, behaving same locally and online
  2. Cookie Setting: IsEssential and Secure are set to true. Domain and Port do not change. Samesite strict, lax or none doesnt make a difference.
  3. The behavior is the same when I'm hosting it on a IIS Server with a public domain having e.g. "subdomain.azure.com"
  4. Returning a View (Status Code 200 Ok) instead of RedirectToAction (Status Code 302) doesn't make a difference.
  5. Cookie Domain with "/" at the end or not doesn't make a difference

I believe I've read all existing questions and answers on stackoverflow with regards to this error and also this article but I could not figure it out.

Could you please advise?


Solution

  • It appears that the domain parameter within the Cookie Options should be just the host name / domain name without protocol and port. E.g. when working locally it should be "localhost".

    Working Set-Cookie:

    afc=test123; expires=Thu, 10 Apr 2025 17:15:54 GMT; domain=localhost; path=/; secure; samesite=lax