How to get all the AD groups for a particular user?

后端 未结 10 1674
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 04:19

I checked this post already. But it doesn\'t answer my question. I want to get all the active directory groups in which a particular user is a member.

I\'ve written

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 05:07

    This code works even faster (two 1.5 faster than my previous version):

        public List GetUserGroups(WindowsIdentity identity)
        {
            List groups = new List();
    
            String userName = identity.Name;
            int pos = userName.IndexOf(@"\");
            if (pos > 0) userName = userName.Substring(pos + 1);
    
            PrincipalContext domain = new PrincipalContext(ContextType.Domain, "riomc.com");
            UserPrincipal user = UserPrincipal.FindByIdentity(domain, IdentityType.SamAccountName, userName); // NGeodakov
    
            DirectoryEntry de = new DirectoryEntry("LDAP://RIOMC.com");
            DirectorySearcher search = new DirectorySearcher(de);
            search.Filter = "(&(objectClass=group)(member=" + user.DistinguishedName + "))";
            search.PropertiesToLoad.Add("cn");
            search.PropertiesToLoad.Add("samaccountname");
            search.PropertiesToLoad.Add("memberOf");
    
            SearchResultCollection results = search.FindAll();
            foreach (SearchResult sr in results)
            {
                GetUserGroupsRecursive(groups, sr, de);
            }
    
            return groups;
        }
    
        public void GetUserGroupsRecursive(List groups, SearchResult sr, DirectoryEntry de)
        {
            if (sr == null) return;
    
            String group = (String)sr.Properties["cn"][0];
            if (String.IsNullOrEmpty(group))
            {
                group = (String)sr.Properties["samaccountname"][0];
            }
            if (!groups.Contains(group))
            {
                groups.Add(group);
            }
    
            DirectorySearcher search;
            SearchResult sr1;
            String name;
            int equalsIndex, commaIndex;
            foreach (String dn in sr.Properties["memberof"])
            {
                equalsIndex = dn.IndexOf("=", 1);
                if (equalsIndex > 0)
                {
                    commaIndex = dn.IndexOf(",", equalsIndex + 1);
                    name = dn.Substring(equalsIndex + 1, commaIndex - equalsIndex - 1);
    
                    search = new DirectorySearcher(de);
                    search.Filter = "(&(objectClass=group)(|(cn=" + name + ")(samaccountname=" + name + ")))";
                    search.PropertiesToLoad.Add("cn");
                    search.PropertiesToLoad.Add("samaccountname");
                    search.PropertiesToLoad.Add("memberOf");
                    sr1 = search.FindOne();
                    GetUserGroupsRecursive(groups, sr1, de);
                }
            }
        }
    

提交回复
热议问题