【问题标题】:How to check if a given user is a member of the built-in Administrators group?如何检查给定用户是否是内置管理员组的成员?
【发布时间】:2008-09-09 16:09:23
【问题描述】:

我需要以编程方式(在 .NET 中)检查给定用户(域帐户)是否是当前计算机(执行应用程序的计算机)上内置管理员组的成员。

有可能吗?

【问题讨论】:

    标签: .net security


    【解决方案1】:

    我不了解 .Net,但在 win32 中,简单的方法是调用 IsUserAnAdmin()。如果您需要更多控制权,您可以打开流程令牌并使用 CheckTokenMembership 检查您需要检查的每个组

    编辑:请参阅pinvoke.net 获取 .NET 示例代码(感谢 Chopeen)

    【讨论】:

      【解决方案2】:

      有一个 Win32 API,您可以 P/Invoke:IsUserAnAdmin

      Vista 上的问题更复杂...请参阅blog post

      【讨论】:

      • "IsUserAnAdmin 函数是 CheckTokenMembership 的封装。建议直接调用该函数来确定管理员组状态,而不是调用 IsUserAnAdmin"。 (来自链接页面)
      • 我之前没有注意到这个警告。我想知道为什么微软会考虑弃用这样一个更简单的助手......幸运的是,他们在向后兼容性方面有着良好的记录。
      【解决方案3】:

      您可以像我在这个答案中所做的那样循环组:

      Determining members of local groups via C#

      阅读更多内容后,最简单的方法是使用System.DirectoryServices.AccountManagement 命名空间。以下是它的使用方法:

      http://www.leastprivilege.com/SystemDirectoryServicesAccountManagement.aspx

      示例:

      public static bool IsUserInGroup(string username, string groupname, ContextType type)
      {
          PrincipalContext context = new PrincipalContext(type);
      
          UserPrincipal user = UserPrincipal.FindByIdentity(
              context,
              IdentityType.SamAccountName,
              username);
          GroupPrincipal group = GroupPrincipal.FindByIdentity(
              context, groupname);
      
          return user.IsMemberOf(group);
      }
      

      【讨论】:

      • System.DirectoryServices.AccountManagement 命名空间是 .NET 3.5 的新名称,不是吗?
      • 链接文章中的第一句话:“在浏览 3.5 的一些新内容时,我偶然发现了一个名为“System.DirectoryServices.AccountManagement”的新程序集——这引起了我的注意。”
      • 对不起,我错过了。您能否在答案中添加信息 CheckTokenMembership 以使其完整(以便我可以将其标记为已接受的答案)?
      【解决方案4】:

      如果你说的是当前正在运行的用户,那么

      using System.Security.Principal;
      
      WindowsIdentity identity = WindowsIdentity.GetCurrent();
      WindowsPrincipal wp = new WindowsPrincipal(identity);
      
      if (wp.IsInRole("BUILTIN\Administrators"))
         // Is Administrator
      else
         // Is Not
      

      如果不是,那么我希望它可以将 identity 设置为特定用户,但没有研究如何设置。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-02
        • 2022-10-02
        • 1970-01-01
        • 2014-05-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多