So we're working on getting a user's full name out of Active Directory services for headers in our webpages. Basically we just want to say "Welcome |your name|" somewhere in the header.
We built and tested a class that seemed to work fine, here's the code snippet:
public class User
{
string loginName;
string fullName;
public User(string LoginName)
{
loginName = LoginName;
fullName = GetDirectoryServiceProperty(loginName, "Name");
}
static string GetDirectoryServiceProperty(string ObjectName, string PropertyName)
{
DirectoryEntry de = new DirectoryEntry("LDAP://yourcompany.com");
DirectorySearcher aSearcher = new DirectorySearcher(de);
StringBuilder filter = new StringBuilder();
filter.AppendFormat("(anr={0})", ObjectName);
aSearcher.Filter = filter.ToString();
SearchResult sr = aSearcher.FindOne();
if (sr == null)
{
throw new NullReferenceException("No such directory entry exists");
}
DirectoryEntry directoryObject = sr.GetDirectoryEntry();
return (string)directoryObject.Properties[PropertyName].Value;
}
public string LoginName { get { return loginName;} }
public string FullName { get { return fullName; } }
}
So we go ahead and deploy this to our web application, which is using windows authentication... and it gives us a null exception.
We poke around a bit and discover even though we were using windows authentication and the Context.User.Identity.Name property was returning a user name, the ASPNET account was the one trying to run the LDAP service which since ASPNET isn't a member of the domain isn't allowed.
Long story short, we added identity impersonate="true" to our web.config and everything started working fine.
