Search code examples
c#azure-active-directoryasp.net-identityblazor

How to get user's attributes from Identity in Blazor Server with organization authentication


In the template provided for authentication you see an email address displayed in the LoginDisplay component, which is what the Name property of ...Identity, as shown below:

<AuthorizeView>
    <Authorized>
        Hello, @context.User.Identity.Name!
        <a href="AzureAD/Account/SignOut">Log out</a>
    </Authorized>
    <NotAuthorized>
        <a href="AzureAD/Account/SignIn">Log in</a>
    </NotAuthorized>
</AuthorizeView>

What I would like to know is how to access other information about an authenticated user. Like a full name, for example, in a simple way. I've found that with Linq you can get data from the Claims property like so:

@context.User.Claims.Where(c => c.Type == "name").FirstOrDefault().Value.ToString()

Is that how we should get that information, or is there a better/preferred way to access that data from an authenticated user?


Solution

  • If you have what is needed in Claims this is the best place to get it from. You could add extra claims to your Identity - see how to do that in Adding extra claims in ASP.NET Core web applications. If it's not enough and you'd like to get full access to your IdentityUser entity inside your authorized component markup, you can do that via AuthenticationStateProvider and UserManager<IdentityUser> by injecting them to your Blazor page.

    @page "/"
    @inject AuthenticationStateProvider AuthenticationStateProvider
    @using Microsoft.AspNetCore.Identity;
    @inject UserManager<IdentityUser> UserManager;
    
    <p>@Details</p>
    
    @code {
    
        private string Details { get; set; }
    
        protected override async Task OnInitializedAsync()
        {
            var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
            var user = authState.User;
    
            if (user.Identity.IsAuthenticated)
            {
                var user = await _UserManager.FindByNameAsync(user.Identity.Name)
                Details = $"Your user phone # is {user.PhoneNumber}.";
            }
            else
            {
                Details = "The user is NOT authenticated.";
            }
        }
    }