Thank you for reaching out to Microsoft Q & A forum.
You are encountering two issues in your Blazor Server application the authenticated user is not appearing in components, and Razor Pages are returning a 401 error despite authentication being configured.
To address these problems, consider following these steps.
1.Use Cookie Authentication for Blazor Server Blazor Server works best with cookies, not JWT. Update your authentication settings in Program.cs:
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
2.Update JwtAuthenticationStateProvider to Read the Authenticated User Modify GetAuthenticationStateAsync to retrieve the user from HttpContext:
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
var user = _acc.HttpContext?.User ?? new ClaimsPrincipal(new ClaimsIdentity());
return Task.FromResult(new AuthenticationState(user));
}
This ensures Blazor Server correctly recognizes the logged-in user.
3.Ensure Razor Pages Have Proper Authorization In Program.cs, enforce authorization on Razor Pages and API controllers:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireAuthorization();
endpoints.MapRazorPages().RequireAuthorization();
});
Also, check HttpContext.User.Identity.IsAuthenticated within Razor Pages to verify authentication.
These changes should help resolve your issues.
Please feel free to contact us if you have any additional questions.
If you have found the answer provided to be helpful, please click on the "Accept answer/Upvote" button so that it is useful for other members in the Microsoft Q&A community.