1

Blazor's component AuthorizeView can display User identity name.

<AuthorizeView>
    <Authorized>
        @context.User.Identity.Name
    </Authorized>
</AuthorizeView>

How can I access to the User variable in the OnInitializedAsync() method in a Blazor page?

IHttpContextAccessor is not an option, because Microsoft insists, you must not use IHttpContextAccessor within Blazor apps.

Browen
  • 75
  • 6
  • https://stackoverflow.com/a/66867028/4990642 Does this answer your question? [Get Current User in a Blazor component](https://stackoverflow.com/questions/60264657/get-current-user-in-a-blazor-component) – Soner from The Ottoman Empire Aug 27 '21 at 06:47
  • @snr, not sure why you've voted to close this question. The answer is wrong... and the asker clearly states that "IHttpContextAccessor is not an option". Incidentally, in the very same thread is my answer, deleted, which is the correct one. I'll undelete it. This answer actually point out to my question and answer (https://stackoverflow.com/a/59538319/6152891). It was original, and later on adopted by the Blazor team to show how to access the HttpContext. My answer in the link you provided was downvoted by an individual so that no one should see the correct answer – enet Aug 27 '21 at 08:49
  • 2
    @Browen, you can simply inject the AuthenticationStateProvider into your component, and then in the life cycle OnInitializedAsync() method call its GetAuthenticationStateAsync() method to retrieve the User object – enet Aug 27 '21 at 08:57
  • @enet your saying is what I point out via the above link. – Soner from The Ottoman Empire Aug 27 '21 at 13:18
  • OK, yes, you're right. This is the correct answer. I didn't read it as it was not the accepted answer... – enet Aug 27 '21 at 16:30

1 Answers1

1

Try this:

var state = await this.GetAuthenticationStateAsync();
ClaimsPrincipal authenticationStateProviderUser = state.User;

to obtain specific information use:

internal static string GetEmail(this ClaimsPrincipal claimsPrincipal)
            => claimsPrincipal.FindFirstValue(ClaimTypes.Email);

to use FindFirstValue you need to add the reference to Microsoft.Extensions.Identity.Core package

Nicola Biada
  • 2,325
  • 1
  • 8
  • 22