Reputation: 4865
I've got a web application that is running against Windows Authentication using our Active Directory. I've got a new requirement to pull some personal information through from the Active Directory entry. What would be the easiest way to get access to this information?
Upvotes: 10
Views: 13966
Reputation: 19142
A very good reference: Howto: (Almost) Everything In Active Directory via C#
Upvotes: 5
Reputation: 13516
You might find the following snippet useful as a starter.
public static bool IsUserInGroup(string lanid, string group)
{
DirectoryEntry entry = new DirectoryEntry("LDAP://" + LDAPPATH);
if(entry != null)
{
entry.Username=@"LDAPUSER";
entry.Password="LDAPPASSWORD";
DirectorySearcher srch = new DirectorySearcher(entry);
srch.Filter = String.Format("(&(objectClass=person)(sAMAccountName={0}))", lanid);
srch.PropertiesToLoad.Add("memberOf");
SearchResult result = srch.FindOne();
if(result != null)
{
if(result.Properties.Contains("memberOf"))
{
string lookfor = String.Format("cn={0},", group.ToLower());
foreach(string memberOf in result.Properties["memberOf"])
{
if(memberOf.ToLower().StartsWith(lookfor))
return true;
}
}
}
return false;
}
throw new Exception(String.Format("Could not get Directory lanid:{0}, group{1}", lanid, group));
}
Upvotes: 5
Reputation: 26344
Accessing the user directly through a DirectoryEntry seems like the most straightforward approach. Here are some AD-related tidbits I learned from my first AD-related project:
You'll probably need to use DirectorySearcher to get your user's directory entry if you don't know its path (which you wouldn't, just by having him logged in). Using it was fairly easy but beware of the quirks in LDAP syntax; namely, having to encode non-ASCII (and other?) characters. The search string you'd use would probably be something like: (&(sAMAccountName=whatever)(class=user)). This is off the top of my head and may be slightly incorrect.
The Active Directory schema reference will be useful. Do understand that the schema can be modified and extended (e.g. installing Exchange will add mailbox information to users).
AD Explorer is a useful tool which you can use for debugging and low-level AD data management. I've found it useful when I know which property I want to set but cannot find the right dialog box in the AD management tool.
Upvotes: 17
Reputation: 12503
Have a look at the System.DirectoryServices namespace:
System.DirectoryServices Namespace
Upvotes: 1
Reputation: 5733
I've used a standard LDAP library to retrieve information from an Active Directory server, but you'd have to verify that the data you need is available via the LDAP server's schema. In general, you can get any information stored in InetOrganizationalPerson and most of the information related to the group(s) they belong to.
Upvotes: 0