Check if user is part of administrator group - C#

做~自己de王妃 提交于 2019-12-12 03:48:58

问题


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


回答1:


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;
   }
}



回答2:


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

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


来源:https://stackoverflow.com/questions/14284730/check-if-user-is-part-of-administrator-group-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!