Home > Blockchain >  ASP.NET Core 6 - Cookie gets returned but not stored in browser
ASP.NET Core 6 - Cookie gets returned but not stored in browser

Time:05-03

I am struggling with Cookie Authentication in Asp.Net Core 6.0

I have implemented and configured the Cookie Authentication and the problem I am facing is the following.

When sending POST request to the login Endpoint which is at <domain>/api/account/login the login returns a 200 OK response and the correct cookie.

However, the Cookie is not getting stored in the browser.

The Cookie Configurations

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
      options.Cookie.Name = "Affito.Identity";
      options.Cookie.HttpOnly = true;
      options.Cookie.SecurePolicy = CookieSecurePolicy.None;
      options.Cookie.SameSite = (SameSiteMode) (-1);
      options.SlidingExpiration = true;
      options.Cookie.Domain = ".affito.ch";
      options.ExpireTimeSpan = TimeSpan.FromMinutes(3);
      options.Cookie.IsEssential = true;
    });

  services.Configure<CookiePolicyOptions>(options =>
  {
    options.MinimumSameSitePolicy = (SameSiteMode)(-1);
    options.HttpOnly = HttpOnlyPolicy.None;
    options.Secure = CookieSecurePolicy.None;
  });

since I have multiple subdomains that need to work with the same cookie I have the .domain attribute in options.Cookie.Domain.

This is the response from the Network Tab in the browser after sending the login request enter image description here

However, the Cookie is getting returned but it is not getting stored in the browser for future requests.

I am sending a simple fetch request from the React-App:

const response = await fetch(BASEURL   "/account/login", {
  method: "POST",
  body: JSON.stringify(loginData),
  headers: {
    "Content-Type": "application/json",
  },
});

console.log(response);

};

Am I missing something or why does it not store the cookie in the browser. I have consulted the docs but could not figure that out.

Swagger: When sending the request from swagger, it returns the same cookie and stores it correctly in the browser. enter image description here

I guessed it had something to do with the 'SameSite' Restriction that's why I took it out but it still does not work when sending the request from stage."domain"

CodePudding user response:

I solved myself. All I had to do was to add the correct CORS policy. If you expect a Cookie to be stored and included in future requests, you must add the Origins and the .WithCredentials() properties to the Cors policy.

It might look something like this:

service.AddCors(options =>
    {
      options.AddPolicy("PolicyName", builder =>
      {
        builder
          .WithOrigins("http://localhost:3000", "https://example.com")
          .AllowAnyHeader()
          .AllowAnyMethod()
          .AllowCredentials();
      });
    });
  • Related