How to determine all the groups a user belongs to (including nested groups) in ActiveDirectory and .NET 3.5

后端 未结 4 1181
情歌与酒
情歌与酒 2020-12-25 13:16

I have an application that uses ActiveDirecotry authorisation and it has been decided that it needs to support nested AD groups, e.g.:

MAIN_AD_GROUP
     |
          


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-25 13:48

    The efficient way is to do a single AD query by having the right DirectorySearcher filter for e.g.

    public bool CheckMemberShip(string userName)
        {
    
            bool membership = false;
            string connection = "LDAP://"+YOURDOMAIN;
            DirectoryEntry entry = new DirectoryEntry(connection);
            DirectorySearcher mySearcher = new DirectorySearcher(entry);
            mySearcher.Filter = "(&(objectClass=user)(memberOf:1.2.840.113556.1.4.1941:=cn=GROUPNAME,OU=Groups,OU=ABC,OU=ABC,OU=IND,DC=ad,DC=COMPANY,DC=com)(|(sAMAccountName=" + userName + ")))";
            SearchResult result = mySearcher.FindOne();
    
            // No search result, hence no membership
            if (result == null)
            {
                membership = false;
            }
    
            entry.Close();
            entry.Dispose();
            mySearcher.Dispose();
    
            membership = true;
            return membership;
        }
    

    You need to replace YOURDOMAIN and GROUPNAME with right values from your AD.

    Source : How to Recursively Get the Group Membership of a User in Active Directory using .NET/C# and LDAP (without just 2 hits to Active Directory)

    Need to include using System.DirectoryServices;

提交回复
热议问题