I have two ASP.NET Core applications:
Blazor Server app with Identity authentication (working correctly)
Web API that should share authentication cookies with the Blazor app
The API is not authenticating users - User.FindFirstValue(ClaimTypes.NameIdentifier) always returns null, even when the user is authenticated in the Blazor app.
Blazor Server Program.cs
builder.Services.AddAuthentication(options =>{ options.DefaultScheme = IdentityConstants.ApplicationScheme; options.DefaultSignInScheme = IdentityConstants.ExternalScheme;}).AddIdentityCookies();builder.Services.AddIdentityCore<User>(options => options.SignIn.RequireConfirmedAccount = false) .AddRoles<IdentityRole>() .AddEntityFrameworkStores<UserdbContext>() .AddSignInManager() .AddDefaultTokenProviders();var app = builder.Build();app.MapAdditionalIdentityEndpoints();Web API Program.cs
builder.Services.AddAuthentication(options =>{ options.DefaultScheme = IdentityConstants.ApplicationScheme; options.DefaultSignInScheme = IdentityConstants.ExternalScheme;}).AddIdentityCookies();builder.Services.AddIdentityCore<BlazorProject.Data.User>(options =>{ options.SignIn.RequireConfirmedAccount = false;}).AddRoles<IdentityRole>().AddEntityFrameworkStores<UserdbContext>().AddSignInManager().AddDefaultTokenProviders();var app = builder.Build();app.UseAuthentication();app.UseAuthorization();API Controller (where authentication fails):
[HttpPost]public async Task<IActionResult> AddUserDeliveryMethod(int methodId){ var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); // Always null // ...}What I've tried:
Both apps use the same database and Identity configuration
Authentication works perfectly in Blazor app
Same cookie schemes configured in both apps
Question:Why isn't the Web API recognizing the authentication cookies from the Blazor Server app, and how can I make them share authentication state properly?
I want to maintain cookie-based authentication and avoid implementing JWT tokens as a solution.