LDAP query to display all groups Is the user a member?

Given the username, how can I write an LDAP query that will return all the groups that the user is a member of?

+3
source share
2 answers

Are you using .NET 3.5 ??

If so, check out this great MSDN article, "Managing Directory Security Principles," in the .NET Framework 3.5 , which shows a new feature for users and groups in .NET 3.5.

In this case, you need the main context (for example, your domain):

PrincipalContext domainContext = 
   new PrincipalContext(ContextType.Domain, "YourDomain");

and then you can easily find the user:

UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, "username");

"UserPrincipal" "GetAuthorizationGroups", , :

PrincipalSearchResult<Principal> results = user.GetAuthorizationGroups();

// display the names of the groups to which the
// user belongs

foreach (Principal result in results)
{
    Console.WriteLine("name: {0}", result.Name);
}

, ?

.NET 3.5 LDAP (PHP, Delphi ..).

+4

:

, System.DirectoryServices.

DirectoryEntry root = new DirectoryEntry("LDAP://OU=YourOrganizationOU,DC=foo,DC=bar");

DirectoryEntry user = GetObjectBySAM("SomeUserName", root);

if (user != null)
{
  foreach (string g in GetMemberOf(user))
  {
    Console.WriteLine(g);
  }
}

, , .

public List<string> GetMemberOf(DirectoryEntry de)
{
  List<string> memberof = new List<string>();

  foreach (object oMember in de.Properties["memberOf"])
  {
    memberof.Add(oMember.ToString());
  }

  return memberof;
}

public DirectoryEntry GetObjectBySAM(string sam, DirectoryEntry root)
{
  using (DirectorySearcher searcher = new DirectorySearcher(root, string.Format("(sAMAccountName={0})", sam)))
  {
    SearchResult sr = searcher.FindOne();

    if (!(sr == null)) return sr.GetDirectoryEntry();
    else
      return null;
  }
}
+1

Source: https://habr.com/ru/post/1716923/


All Articles