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

后端 未结 10 1644
佛祖请我去吃肉
佛祖请我去吃肉 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:10

    Use tokenGroups:

    DirectorySearcher ds = new DirectorySearcher();
    ds.Filter = String.Format("(&(objectClass=user)(sAMAccountName={0}))", username);
    SearchResult sr = ds.FindOne();
    
    DirectoryEntry user = sr.GetDirectoryEntry();
    user.RefreshCache(new string[] { "tokenGroups" });
    
    for (int i = 0; i < user.Properties["tokenGroups"].Count; i++) {
        SecurityIdentifier sid = new SecurityIdentifier((byte[]) user.Properties["tokenGroups"][i], 0);
        NTAccount nt = (NTAccount)sid.Translate(typeof(NTAccount));
        //do something with the SID or name (nt.Value)
    }
    

    Note: this only gets security groups

提交回复
热议问题