您好,我在 ASP.NET 应用程序中使用 Active Directory 和 C#,如果用户位于组中或子组中,我希望得到一个 bool 值。我写了一个方法来获取用户是否在组中但不在这个子组中:(
我如何在我的方法中进行递归搜索:
这是我的代码:
public static bool IsUserInGroup(string dc, string User, string group)
{
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, dc);
GroupPrincipal p = GroupPrincipal.FindByIdentity(ctx, group);
UserPrincipal u = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, User);
bool isMember = u.IsMemberOf(p);
return isMember;
}
static void Main(string[] args)
{
string dc = "company.com";
string user = "test.w";
bool isadmin = IsUserInGroup(dc, user, "TAdmin");
bool isUser = IsUserInGroup(dc, user, "TUser");
Console.WriteLine("Admin: " + isadmin);
Console.WriteLine("User: " + isUser);
Console.ReadLine();
}
代替IsMemberOf
你应该使用的方法GetMembers(Boolean)
与“真实”。它将返回该组的所有成员 - 即使是嵌套的。然后进行循环检查结果中是否有您的用户原则。查看this http://msdn.microsoft.com/en-us/library/bb339975.aspx link.
附加说明:尝试这样的代码
public static bool IsUserInGroup(string dc, string User, string group)
{
bool found = false;
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, dc);
GroupPrincipal p = GroupPrincipal.FindByIdentity(ctx, group);
UserPrincipal u = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, User);
found = p.GetMembers(true).Contains(u);
p.Dispose();
u.Dispose();
return found;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)