asp.net-coreblazor.net-core-3.0blazor-server-sideef-core-3.0

Get Current User in a component


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.


Solution

  • For me the solution mentioned in the first answer 2. option worked perfect: I am using Blazor server side on .Net Core 5.0 . I injected

    @inject AuthenticationStateProvider GetAuthenticationStateAsync
    

    in my Blazor page and added the following in the code section:

    protected async override Task OnInitializedAsync()
        {
            var authstate = await GetAuthenticationStateAsync.GetAuthenticationStateAsync();
            var user = authstate.User;
            var name = user.Identity.Name;
        }
    

    In my startup.cs, I have the following lines:

    services.AddScoped<ApiAuthenticationStateProvider>();
    services.AddScoped<AuthenticationStateProvider>(p =>
                    p.GetRequiredService<ApiAuthenticationStateProvider>());