如何检查用户是否属于AD组? (即使是小组内的小组)

时间:2016-05-23 07:03:00

标签: authentication active-directory active-directory-group

我需要检查登录我正在制作的控制台应用程序的用户是否属于DL(让我们称之为DL-A)。

某些用户不是DL-A的直接组成部分,而是属于DL-A成员的其他DL。我工作的代码只检查用户直接成员的组。我该如何检查?

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain);
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, username);
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "DL-A");

if (user != null)
{
   if (user.IsMemberOf(group))
   {
       ...
   }
}

1 个答案:

答案 0 :(得分:0)

您可以看到用户是否是嵌套组成员的一种方法是获取组recursively中的所有用户。我在您的代码中使用usergroup

....

if (group != null)
{
    var users = group.GetMembers(true); //this will get nested users
    var contains = users.Contains(user);
    if (contains)
    {
       //user found
    }
}

...