Search code examples
c#asp.net-corecookiesasp.net-identityasp.net-core-3.0

Sharing the Identity Login Cookie across subdomains


I am currently working on a ASP.Net Core 3 pre-release 9 MVC Web app. I try to login into my Web App with the same Cookie.

Currently my Startup.cs the ConfigureServices method looks something like the following:

services.ConfigureApplicationCookie(options =>
            {
                options.Cookie.Name = "Auth";
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
                options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
                options.Cookie.HttpOnly = false;

                options.ExpireTimeSpan = TimeSpan.FromDays(31);
                options.LoginPath = "/Auth/SignIn";
                options.SlidingExpiration = true;
                options.Validate();
            });

Then like the other questions on SO said I added something along these lines:

options.Cookie.Domain = ".localhost";

I tried it without the dot, with the port and all possible combinations, but it doesn't work. I also changed the SameSiteMode to any possible option, but it didn't help neither. I can't even see it in the Browser Cookies, until I remove it, it won't work.

Note: All the Subdomains are handled by the same ASP.Net Core app


Solution

  • So it was a bit more complicated in some ways, but the solution is actually pretty simple.

    Localhost gets special treatments in a lot of ways, but also for cookies. In order for a cookie to be accepted by the client e.g. the browser the Domain property needs to contain at least two dots. For localhost you can simple do this by constructing your domain something like .domain.localhost which will solve the issue. Of course you will need to call your website now over the same domain in order to work.