angularcookiesasp.net-core-webapi.net-6.0asp.net-authorization

Cookie not set in Angular project when calling ASP.NET Core 6 Web API despite Set-Cookie header


I'm working with an ASP.NET Core 6 Web API backend that uses cookie authentication, and an Angular frontend.

The backend API runs on http://localhost:5001 and uses Swagger for testing.

When I call the login endpoint through Swagger, the cookie is successfully set in the browser under the localhost domain. However, when I make the same request from my Angular app (running on http://localhost:4200) using a client generated with NSwag, the call succeeds but the cookie is not set despite the Set-Cookie header.

Here's my authentication and cookie setup on the backend:

services.AddAuthentication(options =>
{
    options.DefaultScheme = PrimaryScheme.Name;
    options.RequireAuthenticatedSignIn = true;
})
.AddCookie(PrimaryScheme.Name, options =>
{
    options.ExpireTimeSpan = TimeSpan.FromDays(7);
    options.Cookie.Name = PrimaryScheme.Name;
    options.Cookie.IsEssential = true;
    options.Cookie.SameSite = SameSiteMode.Strict;
    options.Cookie.HttpOnly = true;
    options.Cookie.SecurePolicy = CookieSecurePolicy.None;
})

Here's my CORS policy on the .NET backend:

options.AddPolicy("CorsPolicy", policy => policy
    .WithOrigins("http://localhost:4200")
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials());

Despite this setup, the cookie isn't being stored in the browser when making requests from Angular, although the login call succeeds.

I've tried setting the cookie's domain to "localhost" and other variations of that to fake a domain, but that had no effect.


Solution

  • You are trying to set cross domain cookies.

    You could run both the API and the WebApp under the same domain and port with different paths, localhost:4000/api/...

    Or follow this answer, which should fix your problem. https://stackoverflow.com/a/62777181/9090849