【问题标题】:How to test if AD User is a member of a local group如何测试 AD 用户是否是本地组的成员
【发布时间】:2012-11-24 04:21:32
【问题描述】:

创建新 AD 组的 IT 部门审批流程非常繁琐,因此我的任务是寻找使用本地组来控制访问的方法。

在 Windows Server 2008 R2 上,我创建了一个本地组,并添加了几个其他 AD 组以及一些 AD 用户帐户作为成员。

我需要编写一些 C# 代码来确定特定 AD 用户是否属于特定本地组,其中本地组包含 AD 组和 AD 用户的混合。 AD 组在某些情况下可能包含嵌套的 AD 组。

更新

当域用户帐户直接是本地组的成员时,下面的代码有效,但当本地组包含域用户所属的域组时,它不起作用。

public static void Test()
{
    // returns true, domain user account user623 is in domain group ...
    bool b1 = UserIsInDomainGroup("user623", "apc.app.cartopac.surfaceland");

    // returns true - user623 is directly in local.groupa
    bool b2 = UserIsInlocalGroup("user623", "local.groupa");

    // returns false, even though apc.app.cartopac.surfaceland is in local.groupb
    bool b3 = UserIsInlocalGroup("user623", "local.groupb");
}

public static bool UserIsInDomainGroup(string userName, string grpName)
{
    var domainContext = new PrincipalContext(ContextType.Domain, "contoso");
    var user = UserPrincipal.FindByIdentity(domainContext, userName);
    return user.IsMemberOf(domainContext, IdentityType.Name, grpName);
}

public static bool UserIsInlocalGroup(string userName, string localgrpName)
{
    var machineContext = new PrincipalContext(ContextType.Machine);
    var grpPrincipal = GroupPrincipal.FindByIdentity(machineContext, IdentityType.Name, localgrpName);
    var domainContext = new PrincipalContext(ContextType.Domain, "contoso");
    var user = UserPrincipal.FindByIdentity(domainContext, userName);
    return user.IsMemberOf(grpPrincipal);
}

【问题讨论】:

  • 不能用就用:user.IsMemberOf(grpPrincipal)??这对你有用吗?
  • @marc_s 我已将代码更改为我们的 IsMemberOf,但仍然没有产生预期的结果。
  • 好的。在您所说的第一篇文章中,您想检查用户是否在组中。如果用户在任何嵌套组中,则不会。但这也不是问题。告诉我们您的最终目标是什么,以及如何使用代码。只是向你扔代码可能不是最好的......
  • PrincipalContext 和其他实现 IDisposable 并且必须被释放。此示例代码破坏了该合同并可能泄漏内存(以及其他不好的事情)。在实现 IDisposable 的 using 对象周围添加 using 块。

标签: c# active-directory active-directory-group


【解决方案1】:

假设您将 UserPrincipalName 而不是 sAMAccountName 传递给该方法,您的示例工作正常,并且 contoso 仅在示例中隐藏..

编辑:

试试this。它检查用户是否是成员,即使通过组嵌套:

bool b1 = IsInGroup("sAMAccountName", "LOCALGROUPNAME");


    static bool IsInGroup(string user, string group)
    {
      using (WindowsIdentity identity = new WindowsIdentity(user))
      {
        WindowsPrincipal principal = new WindowsPrincipal(identity);
        return principal.IsInRole(group);
      }
    }

【讨论】:

  • 我对示例进行了一些更新。我想我正在传递一个 UserPrincipalName。这有意义吗?谢谢。
猜你喜欢
  • 1970-01-01
  • 2018-02-27
  • 1970-01-01
  • 2010-11-05
  • 1970-01-01
  • 1970-01-01
  • 2019-04-30
  • 1970-01-01
  • 2023-04-11
相关资源
最近更新 更多