How to get user's first name or last name from @context.User?

Viewed 5253

I created a Server side Blazor application using Windows authentication. And it created the following file.

LoginDisplay.razor

<AuthorizeView>
    Hello, @context.User.Identity.Name!
</AuthorizeView>

However, it shows "DOMAIN\username". Is it a way to show the user first name?

I tried to print all the claim types.

@foreach(var c in context.User.Claims)
{
    <p>@c.Value @c.Type</p>
}

However, there is only one type with name in it. (with value of DOMAIN\username)

http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name
3 Answers

You can also use it as below using the Directory Services (install using NuGet).

_Imports.razor

@using System.DirectoryServices.AccountManagement

LoginDisplay.razor

<AuthorizeView>
    @{
        var pcontext = new PrincipalContext(ContextType.Domain, "XYZ.net", "DC=XYZ,DC=net");
        var principal = UserPrincipal.FindByIdentity(pcontext, context.User.Identity.Name);
    }    
    Hello, @principal.GivenName @principal.Surname!
</AuthorizeView>

You have to go out to AD for that information. But connecting to AD in ASP.NET Core isn't straight-forward.

If you are only going to run this on a Windows server, then you can install Microsoft.Windows.Compatibility from NuGet, and use DirectoryEntry to bind directly to the object using its SID. The SID is available in context.User.Identity.User.Value.

<AuthorizeView>
@{
    var identity = (WindowsIdentity) context.User.Identity;
    var user = new DirectoryEntry($"LDAP://<SID={identity.User.Value}>");

    //Add any other attributes you want to read to this list
    user.RefreshCache(new [] { "givenName" });
}
    Hello, @user.Properties["givenName"].Value!
</AuthorizeView>

Other attributes you might be interested in:

  • sn: Last name
  • displayName: How their name is displayed in Outlook, for example. Often this is "Last, First"

I try this in blazor web assembly. and API using asp.net core 6 and its works as i expected
here is the code

List<Claim> claims = new List<Claim>
        {
            new Claim(ClaimTypes.NameIdentifier,user.Id.ToString()),
            new Claim(ClaimTypes.Email,user.Email),
            new Claim(ClaimTypes.Name,user.FirstName + " " + user.LastName),
            new Claim(ClaimTypes.Surname,user.LastName)

        };

I just return the Name with Firstname then +"give space here"+ give Lastname

and it gives me results using

@context.User.Identity.Name

Hi! You're logged in with Vikas Admin.

Admin is the last name of the user.

Thankyou

Related