Search code examples
asp.net-mvcasp.net-coreauthenticationcookies

How to clear authentication cookie when use it as subdomain domain cookie?


In .Net Core using below code to make authentication cookie:

builder.Services.AddAuthentication(options =>
  {
   options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
   options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
   options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
  .AddCookie(options =>
          {
              options.SlidingExpiration = false;
              options.LoginPath = "/Accounts/Login";
              options.LogoutPath = "/Accounts/Logout";
              options.AccessDeniedPath = new PathString("/Accounts/Forbidden/");
              options.Cookie.Name = "mycookie";
              options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
              options.Cookie.SameSite = SameSiteMode.Strict;
              
          });

and delete it in a controller:

await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

it works OK but if use cookie like below:

options.Cookie.Domain = ".example.com"; 

it doesn't delete authentication cookie anymore.


Solution

  • Well, based on your scenario and description when you would use CookieOptions property SameSite to SameSiteMode.Strict it would no longer track cross-site cookie in your case sub-domain cookie. Thus, in order to use cookie in cross-site or sub-domain you need to set SameSiteMode.None for options.Cookie.SameSite.

    Please have a look below:

    enter image description here

    enter image description here

    Note: Please refer to this official document for details configuration on samesite cookie.