C# ActiveDirectory LDAP Group Querying
active-directory, c#, ldap
Solution
Yes, the "usual" `user.Properties["memberOf"]` only returns direct memberships.
If you're using .NET 3.5 however, you can use the more modern "principal-based" methods:
using(PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
using(Principal p = Principal.FindByIdentity(ctx, "yourUserName"))
{
var groups = p.GetGroups();
using (groups)
{
foreach (Principal group in groups)
{
Console.WriteLine(group.SamAccountName + "-" + group.DisplayName);
}
}
}
}
This method (add a reference to the "System.DirectoryServices.AccountManagement" assembly to your project) should work and deliver the user's primary group and its nested group memberships as well.
If you're on .NET 2.0/3.0 and can't move up, using the approach by reading the "tokenGroups" attribute is the best approach - see the details about how to do all of this in Ryan Dunn's excellent blog post, Enumerating Token Groups (tokenGroups) in .NET.
Marc
Problem
Basically what I'm trying to do is, I have an ASP.Net web application that's using Forms Authentication with some custom code to link it to ActiveDirectory (very similar to how this works). However, whenever I query the domain controller for the users groups it only returns the groups that they're explicitly in and not subgroups (id est, there's a specific Security Group that the user belongs to, say group A, that is a member of the group I want, say group B, the user is explicitly in group A, but only implicitly in group B because group A is a member of group B). I've read the tokenGroups querying could help me out here but currently I don't have a way to parse that data. However what would be most preferable is if I could pass certain groups via an LDAP query and have the Domain controller just give me a boolean (true/false) if that user is within that group or not. Any suggestions?