检查用户是否是管理员组的一部分-C# [英] Check if user is part of administrator group - C#

查看:71
本文介绍了检查用户是否是管理员组的一部分-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;
            }
        }
    } }

但是,如果用户位于AD组中,并且该AD组已添加到管理员组中。另一种情况是用户是嵌套AD组的一部分,而最后一个AD组又添加到了管理员组中。

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.

我们如何检查用户是否属于管理员组?直接添加并在相关AD组存在的情况下?

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

我想使代码在Windows Server 2008、2008 R2和2012上运行

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

推荐答案

为什么不像以前那样查找用户的所有AD组,然后检查该组是否存在于Administrators组中?您可以按照解决方案此处。然后,您可以修改搜索条件,例如:

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

这篇关于检查用户是否是管理员组的一部分-C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆