.net - 快速获取群组成员资格

标签 .net windows membership active-directory-group

我试图弄清楚当前的 Windows 用户是本地管理员还是可以使用 UAC 来“获得”该组成员身份。

到目前为止,我得出的结论是这样的:

var adminIdentifier = new SecurityIdentifier("S-1-5-32-544");
var current = WindowsIdentity.GetCurrent();
bool isAdmin = current.Groups.Contains(adminIdentifier);
bool canBeAdmin = isAdmin;

if (!isAdmin)
{
    var adminGroupName = adminIdentifier.Translate(typeof(NTAccount)).Value;
    adminGroupName = adminGroupName.Substring(adminGroupName.LastIndexOf('\\'));
    string path = "WinNT://./" + adminGroupName + ",group";

    using (DirectoryEntry groupEntry = new DirectoryEntry(path))
    {
      foreach (object member in (IEnumerable)groupEntry.Invoke("Members"))
      {
        using (DirectoryEntry memberEntry = new DirectoryEntry(member))
        {
              object obVal = memberEntry.Properties["objectSid"].Value;
              SecurityIdentifier sid = null;
              if (null != obVal)
              {
                 sid = new SecurityIdentifier((Byte[])obVal,0);
              }

              canBeAdmin = Equals(current.User, sid);
              if (canBeAdmin)
                break;
        }
     }
   }
 }
 Console.WriteLine(canBeAdmin +" "+isAdmin);

此解决方案需要几毫秒的时间来计算。比我之前尝试过的基于 System.DirectoryServices.AccountManagement 的方法快得多。

不过,还有最后一件事困扰着我。我必须将管理员组的 SecurityIdentifier 翻译成名称。应该有办法得到 直接使用 SID 的 DirectoryEntry。据谷歌称,这应该有效:

string path = "LDAP://<SID=" + adminIdentifier.ToString() + ">";

但是,这似乎行不通。知道语法应该是什么样子吗?

最佳答案

你试过了吗WindowsPrincipal.IsInRole

WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
wp.IsInRole(new SecurityIdentifier("S-1-5-32-544"));
wp.IsInRole(WindowsBuiltInRole.Administrator);

关于.net - 快速获取群组成员资格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/716951/

相关文章:

.net - Linq - 是否有我缺少的 IEnumerable.ForEach<T> 扩展方法?

c# - 检查 Double 是否为 "NaN"的最短方法

c# - 如何在 .NET 2.0 中获取 Environment.SpecialFolders.MyVideo 文件夹?

c++ - Qt in Visual Studio 2013 with cmake - 我如何让它工作?

.NET HttpRequests使用Windows系统Cache

asp.net - 是否可以使用成员(member)用户 ID 检索用户个人资料?

php - 用户通过Facebook登录后,我应该如何处理用户数据

c# - 使用外部事件打破 while 循环

c# - 如何反序列化包含多维数组的json对象?

c# - 我应该检查我的 ASP.NET MVC 应用程序的哪一层成员信息?