User Management with Active Directory—Technique 1: Using an LDAP Search
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:Articles |
| C# Articles |
|
© 2006 Pearson Education, Inc. |
Technique #1: Using an LDAP Search
The big upshot to this approach is that this technique is pretty fast and we don’t have to worry about using any P/Invoke code that can be intimidating to less-experienced developers. We simply iterate through the returned attribute and build a large LDAP filter that represents each security group. Once we build the filter, we can easily search the domain for the groups and return each one. Listing 10.19 shows how we can accomplish this.
Listing 10.19: Retrieving Token Groups with an LDAP Search
StringBuilder sb = new StringBuilder(); //we are building an ’|’ clause sb.Append("(|"); foreach (byte[] sid in user.Properties["tokenGroups"]) { //append each member into the filter sb.AppendFormat( "(objectSid={0})", BuildFilterOctetString(sid)); } //end our initial filter sb.Append(")"); DirectoryEntry searchRoot = new DirectoryEntry( "LDAP://DC=domain,DC=com", null, null, AuthenticationTypes.Secure ); using (searchRoot) { //we now have our filter, we can just search for the groups DirectorySearcher ds = new DirectorySearcher( searchRoot, sb.ToString() //our filter ); using (SearchResultCollection src = ds.FindAll()) { foreach (SearchResult sr in src) { //Here is each group now... Console.WriteLine( sr.Properties["samAccountName"][0]); } } } private string BuildFilterOctetString(byte[] bytes) { //see listing 4.2 for the complete code }
We rely on the helper method called BuildFilterOctetString from Listing 4.2 in Chapter 4 to format the binary SID correctly into a format we can use for our filter. This technique is fairly simple and relatively elegant. It is a great solution when we want to get more information about each group than just the name. The downside is that we don’t directly have access to the DOMAIN\GroupName format from SearchResult. That would require string parsing, an additional search to find the NetBIOS name of the domain from the configuration partition, or a call to DsCrackNames to convert the name appropriately into our chosen format. Since DOMAIN\GroupName happens to be one of the most widely used formats, this tends to be its major drawback.
Notice that we use the sAMAccountName attribute to identify the group. This is important, as the sAMAccountName is used for security purposes and is unique in the domain. We often see samples that parse the DN to retrieve the group’s CN. However, a CN can be duplicated in different containers in the same domain, so we can accidentally introduce security flaws by assuming it is unique. Always use a unique identifier intended for security purposes when making security decisions!
|

