Get Current User in a Blazor component

There are three possibilities for getting the user in a component (a page is a component):

  1. Inject IHttpContextAccessor and from it access HttpContext and then User; need to register IHttpContextAccessor in Startup.ConfigureServices, normally using AddHttpContextAccessor. Edit: according to the Microsoft docs you must not do this for security reasons.
  2. Inject an AuthenticationStateProvider property, call GetAuthenticationStateAsync and get a User from it
  3. Wrap your component in a <CascadingAuthenticationState> component, declare a Task<AuthenticationState> property and call it to get the User (similar to #2)

See more here: https://learn.microsoft.com/en-us/aspnet/core/security/blazor.

Leave a Comment