See if user is part of Active Directory group in C# + Asp.net

前端 未结 14 1284
花落未央
花落未央 2020-11-30 19:06

I need a way to see if a user is part of an active directory group from my .Net 3.5 asp.net c# application.

I am using the standard ldap authentication example off o

14条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 19:56

    If you want to check the user groups membership including the nested groups which is indirectly linked to the user parent group you can try use the "tokenGroups" properties as below:

    Using System.DirectoryServices
    
     public static bool IsMemberOfGroupsToCheck(string DomainServer, string LoginID, string LoginPassword)
            {
                string UserDN = "CN=John.Doe-A,OU=Administration Accounts,OU=User Directory,DC=ABC,DC=com"
                string ADGroupsDNToCheck = "CN=ADGroupTocheck,OU=Administration Groups,OU=Group Directory,DC=ABC,DC=com";
    
                byte[] sid, parentSID;
                bool check = false;
                DirectoryEntry parentEntry;
                DirectoryEntry basechildEntry;
                string octetSID;
    
                    basechildEntry = new DirectoryEntry("LDAP://" + DomainServer + "/" + UserDN, LoginID, LoginPassword);
                    basechildEntry.RefreshCache(new String[] { "tokenGroups" });
    
                    parentEntry = new DirectoryEntry("LDAP://" + DomainServer + "/" + ADGroupsDNToCheck, LoginID, LoginPassword);
                    parentSID = (byte[])parentEntry.Properties["objectSID"].Value;
                    octetSID = ConvertToOctetString(parentSID, false, false);
    
                    foreach(Object GroupSid in basechildEntry.Properties["tokenGroups"])
                    {
                        sid = (byte[])GroupSid;
                        if (ConvertToOctetString(sid,false,false) == octetSID)
                        {
                            check = true;
                            break;
                        }
                    }
    
                    basechildEntry.Dispose();
                    parentEntry.Dispose();
    
                    return check;
            }
    

提交回复
热议问题