
ASP.NET Connecting to an (LDAP) Active Directory Server
October 4, 2011There are many things that you can do with an Active Directory (AD) server – query users, groups, and so on. It can also be used instead of Windows Authentication, and usually will bypass any username/password logon boxes for non-IE browsers. For my purposes, I need to figure out if user X is in group Y.
Here’s what I have:
public static Boolean isHealthServices(String username)
{
bool isInRole = false;
String domainname = "something.org";
String conProperties = "CN=Users,DC=something";
String domainqueryusername = "username";
String domainqueryuserpwd = "password";
String group = "CN=GroupY";
using (var ctx = new PrincipalContext(ContextType.Domain, domainname, conProperties, domainqueryusername, domainqueryuserpwd))
{
using (var grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, group))
{
isInRole = grp != null && grp.GetMembers(true).Any(m => m.SamAccountName == username);
}
}
return isInRole;
}
But, I encounter lots of errors.
The Server Could Not Be Contacted
As it says, it really can’t even find the server. The first thing to do is doublecheck your domainname. Next, check the properties that you are using.
There Is No Such Object On The Server
Your connection properties are wrong. I found that this tool, BeaverTail, is especially useful for figuring out where you are going wrong. You can traverse the LDAP server as ASP.NET would (especially since it is written in C#). The tool is free.
A Referral Was Returned From The Server
Make sure that you prefix the username with the domain. For example “GLaDOS\bob” .
This can also occur if your connection properties aren’t traversing to the correct place. Check the properties that you are using.
A Local Error Has Occurred
This can occur if you used a “/” instead of a “\” in the username. (Note that ASP.NET uses “\” as it’s escape character so “\\” will accomplish this).
An Operations Error Occurred
This one is related to permissions. You’ll want to look into your IIS settings, asp.net user account permissions, and impersonation in your web.config file.