See if user is part of Active Directory group in C

2020-01-27 10: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 of msdn but I don't really see how to check against a group.

13条回答
家丑人穷心不美
2楼-- · 2020-01-27 10:40

With 3.5 and System.DirectoryServices.AccountManagement this is a bit cleaner:

public List<string> GetGroupNames(string userName)
{
  var pc = new PrincipalContext(ContextType.Domain);
  var src = UserPrincipal.FindByIdentity(pc, userName).GetGroups(pc);
  var result = new List<string>();
  src.ToList().ForEach(sr => result.Add(sr.SamAccountName));
  return result;
}
查看更多
ゆ 、 Hurt°
3楼-- · 2020-01-27 10:42

The code below will work in .net 4.0

private static string[] GetGroupNames(string userName)
{
    List<string> result = new List<string>();

    using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))
    {
        using (PrincipalSearchResult<Principal> src = UserPrincipal.FindByIdentity(pc, userName).GetGroups(pc))
        {
            src.ToList().ForEach(sr => result.Add(sr.SamAccountName));
        }
    }

    return result.ToArray();
}
查看更多
女痞
4楼-- · 2020-01-27 10:45

Here is my 2 cents.

    static void CheckUserGroup(string userName, string userGroup)
    {
        var wi = new WindowsIdentity(userName);
        var wp = new WindowsPrincipal(wi);

        bool inRole = wp.IsInRole(userGroup);

        Console.WriteLine("User {0} {1} member of {2} AD group", userName, inRole ? "is" : "is not", userGroup);
    }
查看更多
劳资没心,怎么记你
5楼-- · 2020-01-27 10:47

You could try the following code:

public bool Check_If_Member_Of_AD_Group(string username, string grouptoCheck, string domain, string ADlogin, string ADpassword)
{
    
     try {
        
        string EntryString = null;
        EntryString = "LDAP://" + domain;
        
        DirectoryEntry myDE = default(DirectoryEntry);
        
        grouptoCheck = grouptoCheck.ToLower();
        
        
        myDE = new DirectoryEntry(EntryString, ADlogin, ADpassword);
        
        DirectorySearcher myDirectorySearcher = new DirectorySearcher(myDE);
        
        myDirectorySearcher.Filter = "sAMAccountName=" + username;
        
        myDirectorySearcher.PropertiesToLoad.Add("MemberOf");
        
        SearchResult myresult = myDirectorySearcher.FindOne();
        
        int NumberOfGroups = 0;
        
        NumberOfGroups = myresult.Properties["memberOf"].Count - 1;
        
        string tempString = null;
        
        while ((NumberOfGroups >= 0)) {
            
            tempString = myresult.Properties["MemberOf"].Item[NumberOfGroups];
            tempString = tempString.Substring(0, tempString.IndexOf(",", 0));
            
            tempString = tempString.Replace("CN=", "");
            
            tempString = tempString.ToLower();
            tempString = tempString.Trim();
            
            if ((grouptoCheck == tempString)) {
                
                    
                return true;
            }
            
                
            NumberOfGroups = NumberOfGroups - 1;
        }
        
            
        return false;
    }
    catch (Exception ex) {
        
        System.Diagnostics.Debugger.Break();
    }
    //HttpContext.Current.Response.Write("Error: <br><br>" & ex.ToString)
}
查看更多
狗以群分
6楼-- · 2020-01-27 10:47

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;
        }
查看更多
登录 后发表回答