Monday, May 17, 2004

ASP .NET impersonation and LDAP

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://");
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 apparently is illegal by default.

Long story short, we added identity impersonate="true" to our web.config and everything started working fine.


At 3:09 PM, Blogger oni said...

it doesn't just seem to work fine.

The problem is with permissions, of course.

Specifically, (local)\ASPNET is not a member of the (redacted) domain, so it had no rights to search the directory.

Impersonation is an option. Webservice with elevated privileges (RunAs a domain user) is another. There may be further options, as well. A permission assert guarding the actual DirectoryServices interactions comes to mind - we'd need to strongname the assembly and do a couple other things that make this the Simple solution - Correct is arguable depending on the exposure of the functionality, and whether we'll ever need to NOT imitate the user.


Post a Comment

<< Home