简体   繁体   中英

Check if user is part of administrator group - C#

I have code to verify if user is present in administrator group on local machine. The code works fine if user is directly present in administrator group

using (DirectoryEntry groupEntry = new DirectoryEntry("WinNT://./Administrators,group")) {
    foreach (object member in (IEnumerable)groupEntry.Invoke("Members"))
    {
        using (DirectoryEntry memberEntry = new DirectoryEntry(member))
        {
            if (memberEntry.Name.ToLower() == UserName.ToLower())
            {
                IsUserAdmin = true;
                break;
            }
        }
    } }

But the code fails if user is present in an AD group and that AD group is added in administrator group. Another case is user is part of nested AD group and the final AD group is added in administrator group.

How can we check if user is part of administrator group when he is directly added and when related AD group is present?

I want to make the code work on Windows Server 2008, 2008 R2 and 2012

Why not just find all the AD groups for the user and then check if the group exists in Administrators group like before ? You can find all AD groups for a user by following the solution here . You can then modify your search criteria like:

var adminGroupMembers = (IEnumerable)groupEntry.Invoke("Members");
....
//where userGroups contains all AD group names to which user belongs to
foreach(var group in userGroups)
{ 
   if(adminGroupMembers.Contains(group))
   {
      IsUserAdmin = true;
      break;
   }
}

This would work to tell if they are part of admin group:

    WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
    return principal.IsInRole(WindowsBuiltInRole.Administrator);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM