Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

ASP.NET Core Web API not authenticating with Identity cookies from Blazor Server app

$
0
0

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.


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>