I've tried to load all groups for a user from LDAP.
Currently I'm testing on our local AD. With the following code I can load all groups of the given user:
public IEnumerable<String> GetUserGroups( String userName )
{
using ( var domainContext = new PrincipalContext( ContextType.Domain, Name ) )
{
var user = UserPrincipal.FindByIdentity( domainContext, userName );
return user.GetAuthorizationGroups().Select( x => x.Name} ).ToList();
}
}
But I fail to get the same result using LDAP.
Code using LDAP:
public IEnumerable<String> GetUserGroups1(String userName)
{
//returns the container name of the given user
var containerName = GetUserContainerName(userName);
var groups = new List<String>();
if (containerName == null)
return groups;
var entry = new DirectoryEntry(String.Format("LDAP://{0}", "DC=example,DC=com"));
var searcher = new DirectorySearcher(entry)
{
Filter = String.Format("(member:{0}:=CN={1},{2},{3})",
"1.2.840.113556.1.4.1941",
containerName, "CN=Users", "DC=example,DC=com"),
SearchScope = SearchScope.Subtree
};
var result = searcher.FindAll();
for (var i = 0; i < result.Count; i++)
{
var path = result[i].Path;
var startIndex = path.IndexOf("CN=", StringComparison.Ordinal) + 3;
groups.Add(path.Substring(startIndex, path.IndexOf(",", startIndex + 1,
StringComparison.Ordinal) - startIndex));
}
return groups;
}
How can I get all groups for a user using LDAP?
My first advice is you should split your method in sort of having a better overview:
You could use something like that:
/// <summary>
/// Return the user by the user name
/// </summary>
/// <param name="userName_">Username to base search on</param>
/// <returns>
/// User Manager or null if not found
/// </returns>
public static DirectoryEntry SearchForUser(string userName_)
{
DirectoryEntry de = null;
DirectorySearcher directorySearcher = null;
Domain domain = null;
try
{
if (String.IsNullOrEmpty(userName_))
return null;
string userName = userName_.StartsWith("CN=") ? userName_.Replace("CN=", String.Empty) : userName_;
de = new DirectoryEntry("LDAP://" + Domain.GetCurrentDomain().Name);
directorySearcher = new DirectorySearcher(de);
directorySearcher.Filter = string.Format("(&(objectClass=person)(objectCategory=user)(sAMAccountname={0}))", userName);
SearchResult searchResult = directorySearcher.FindOne();
return searchResult != null ? searchResult_.GetDirectoryEntry() : null;
}
finally
{
if (de != null)
de.Dispose();
if (directorySearcher != null)
directorySearcher.Dispose();
if (domain != null)
domain.Dispose();
}
}
This way, you can valid the LDAP path, domain name, domain
Use a second method to clearly and simply get the groups.
/// <summary>
///Returns a list with the groups where this user is a member of.
/// </summary>
/// <remarks>The members in the returned list are instances of Group.</remarks>
/// <returns>Groups where this user is member of.</returns>
public List<DirectoryEntry> GetGroups()
{
return (from object o in Entry.Properties["memberOf"]
select new DirectoryEntry(path)
into dirEntry
where dirEntry.SchemaClassName == "group"
select {DirectoryEntry = dirEntry}).ToList();
}
Where path is your OU path (root, or not).
The biggest challenge is managing and building the LDAP path.
I hope that helped.