Thomas Svensen
Thomas Svensen

Reputation: 800

Retrieve additional user properties from ActiveDirectoryMembershipProvider

The ActiveDirectoryMembershipProvider in ASP.NET returns users as instances of MembershipUser. This class only returns two of the properties defined for the given user in AD: email and username. I need to get access to additional properties, specifically "DisplayName", as I need to show full names in a dropdown in a web form.

The only way I can find to do this, is via a separate connection to AD, along the lines of what is described here: How can I convert from a SID to an account name in C#. This seems like a cumbersome and inefficient solution. I would like to do something like membershipProvider.GetUserProperty(username, propertyName), but that's not available.

Are there any nice solutions that people know of?

Upvotes: 0

Views: 899

Answers (1)

Thomas Svensen
Thomas Svensen

Reputation: 800

Based on feedback from my colleagues (thanks, Eirik!), @KennyZ's comment and lots of Googl'ing, I have found that this is the best/only way to do it. For reference, and other people seeing this question, here is some useful code for getting the AD settings out of web.config+connectionStrings.config, and using that data to query AD for a given user's Display Name:

var membershipSection = (MembershipSection)WebConfigurationManager.GetSection("system.web/membership");
var providerSettings = membershipSection.Providers["ActiveDirectoryMembershipProvider"];
var connectionStringName = providerSettings.Parameters["connectionStringName"];
var adUser = providerSettings.Parameters["connectionUsername"];
var adPassword = providerSettings.Parameters["connectionPassword"];
var adConnection = WebConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
var adReference = new DirectoryEntry(adConnection, adUser, adPassword);
var search = new DirectorySearcher(adReference) {Filter = string.Format("(mail={0})", username)};
search.PropertiesToLoad.Add("displayName");
SearchResult result = search.FindOne();
if (result != null)
{
    var resultCollection = result.Properties["displayName"];
    if (resultCollection.Count > 0)
    {
        var displayName = resultCollection[0].ToString();
        ...
    }
}

Note: This assumes that I am using userPrincipalName as the attributeMapUsername in web.config, as that maps to the user's email address.

Upvotes: 1

Related Questions