Serj Sagan
Serj Sagan

Reputation: 30208

How to get Active Directory current user Display Name in ASP.NET Core?

I am using C# ASP.NET Core (MVC 6) against an on-prem Active Directory setup. I can get the current user's username simply by

public MyModel(IHttpContextAccessor httpContextAccessor)
{
    string userName = httpContextAccessor.HttpContext.User.Identity.Name;
}

Which gives me "DOMAIN\jsmith" However, I need to get at the Display Name, i.e. "John Smith". How do I do this?

Update: After more digging, this does not seem to be currently available: https://github.com/dotnet/corefx/issues/2089

Upvotes: 4

Views: 8298

Answers (3)

Darkknight
Darkknight

Reputation: 1

Had the same issue. After some research and browsing the Microsoft Docs, I found the solution.

First install the System.DirectoryServices.AccountManagement package using Nuget Package Manager.

Then while calling the GetUserNameWithoutDomain method pass the following as the parameters:

GetUserNameWithoutDomain(UserPrincipal.Current.GivenName, UserPrincipal.Current.Surname);

Upvotes: -2

blowdart
blowdart

Reputation: 56500

The Novell ldap library has been ported to .NET Core. As Display Name is an attribute you should be able to use the library to query for it (although there's no specific sample)

Upvotes: 4

oldovets
oldovets

Reputation: 705

You need to create a connection to Active Directory, find user by it's sAMAccountName attribute and query it's displayName attribute.

var domain = httpContextAccessor.HttpContext.User.Identity.Name.Split('\\').First();
var accountName = httpContextAccessor.HttpContext.User.Identity.Name.Split('\\').Last();

using (var entry = new DirectoryEntry($"LDAP://{domain}"))
{
    using (var searcher = new DirectorySearcher(entry))
    {
        searcher.Filter = $"(sAMAccountName={name})";
        searcher.PropertiesToLoad.Add("displayName");
        var searchResult = searcher.FindOne();

        if (searchResult != null && searchResult.Properties.Contains("displayName"))
        {
            var displayName = searchResult.Properties["displayName"][0];
        }
        else
        {
            // user not found
        }
    }
}

Upvotes: -1

Related Questions