How do I filter an LDAP query for groups containin

2019-01-19 03:29发布

问题:

How do I filter an Active Directory LDAP query to groups containing the authenticated/bound user (or any user at all)? This works fine:

(&(objectClass=group)(member=*))
>>> lots of results

But I can't go any more detail:

(&(objectClass=group)(member=*S*))
>>> nothing

The MSDN mentions using a filter like this:

(member:1.2.840.113556.1.4.1941:=(cn=user1,cn=users,DC=x))

But even ignoring the crazy hyper magic number involved in that, I always get 0 results when I try to filter with that (even replacing cn=user1,cn=users,DC=x with my own distinguishedName, even replacing it with *).

回答1:

You need the full DN of the user i.e

(&(member=CN=Your Name,OU=Your OU,DC=company,DC=com)(objectClass=group))

take note you cannot use * in this one



回答2:

So the crazy hyper magic number involved in recursive search is explained in Search Filter Syntax.

To find in one search (recursively) all the groups that "user1" is a member of:

  • Set the base to the groups container DN; for example root DN (dc=dom,dc=fr)
  • Set the scope to subtree
  • Use the following filter: (member:1.2.840.113556.1.4.1941:=cn=user1,cn=users,DC=x)

explicited using LDIFDE.EXE the command line tool included in Windows Server it gives:

ldifde -f user1Grps.ldf -d "dc=societe,dc=local" -r "(member:1.2.840.113556.1.4.1941:=cn=user1,ou=Monou,dc=societe,dc=local)"

If you are running that on a W2K8 or W2K8 R2 server be careful to run as administrator.

If you are programming in C# you can use:

/* Retreiving a principal context
 */
Console.WriteLine("Retreiving a principal context");
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "WM2008R2ENT:389", "dc=dom,dc=fr", "jpb", "PWD");


/* Look for all the groups a user belongs to
 */
UserPrincipal aUser = UserPrincipal.FindByIdentity(domainContext, "user1");
PrincipalSearchResult<Principal> a =  aUser.GetAuthorizationGroups();

foreach (GroupPrincipal gTmp in a)
{
  Console.WriteLine(gTmp.Name);    
}