I'm starting a new site with Blazor and Windows Authentication and need to identify the current user viewing the page/component.
For a Razor Page, the current user name can be accessed with Context.User.Identity.Name
, but that doesn't seem to work in a Blazor component. I've tried injecting HttpContext into the component but the Context is null at runtime.
As a bonus, I will eventually want to incorporate this into Startup.cs so I only need to get the username once and can leverage a corporate user class (with EF Core) for my applications. Answers tailored to that use case would also be appreciated.
There are three possibilities for getting the user in a component (a page is a component):
IHttpContextAccessor
and from it access HttpContext
and then User
; need to register IHttpContextAccessor
in Startup.ConfigureServices
, normally using AddHttpContextAccessor
AuthenticationStateProvider
property, call GetAuthenticationStateAsync
and get User
from it<CascadingAuthenticationState>
component, declare a Task<AuthenticationState>
property and call it to get the User
(similar to #2)See more here: https://docs.microsoft.com/en-us/aspnet/core/security/blazor.