简体   繁体   English

检查用户是否属于管理员组 - C#

[英]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.但是,如果用户存在于 AD 组中并且该 AD 组已添加到管理员组中,则代码将失败。 Another case is user is part of nested AD group and the final AD group is added in administrator group.另一种情况是用户是嵌套 AD 组的一部分,最终的 AD 组添加到管理员组中。

How can we check if user is part of administrator group when he is directly added and when related AD group is present?当用户被直接添加以及相关的 AD 组存在时,我们如何检查用户是否属于管理员组?

I want to make the code work on Windows Server 2008, 2008 R2 and 2012我想让代码在 Windows Server 2008、2008 R2 和 2012 上运行

Why not just find all the AD groups for the user and then check if the group exists in Administrators group like before ?为什么不直接找到用户的所有 AD 组,然后像以前一样检查该组是否存在于管理员组中? You can find all AD groups for a user by following the solution here .您可以按照此处的解决方案查找用户的所有 AD 组。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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