CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Eric Wise

Business & .NET

Getting the full name from Active Directory

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.



Comments

Sam said:

To do impersonification do a call to the LogonUser API call.
# December 16, 2004 10:37 PM

Neal said:

"To do impersonification do a call to the LogonUser API call."

He said he wanted to impersonate from a new thread and LogonUser API is too flaky for that.

# March 1, 2007 11:55 PM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add
Check out Devlicio.us!