C# 慢速广告组成员查找
我有一些代码来检查域用户是否是machines administrators组的成员:C# 慢速广告组成员查找,c#,active-directory,ldap-query,C#,Active Directory,Ldap Query,我有一些代码来检查域用户是否是machines administrators组的成员: public static bool ActiveDirectoryGroupMembershipOk(string userid, string groupName) { using (PrincipalContext ctx = new PrincipalContext(ContextType.Machine, "my_pc_name")) { using (GroupPr
public static bool ActiveDirectoryGroupMembershipOk(string userid, string groupName)
{
using (PrincipalContext ctx = new PrincipalContext(ContextType.Machine, "my_pc_name"))
{
using (GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "administrators"))
{
if (grp != null)
{
foreach (Principal p in grp.GetMembers(false))
{
if (p is UserPrincipal && p.SamAccountName.Equals(userid, StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
}
}
}
}
return false;
}
它可以工作,但下面的代码行需要几秒钟才能完成:
using (GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "administrators"))
有没有更快的方法查找成员资格
我不知道这是否重要,但用户ID是域用户,windows组位于本地PC上。我发现,不在组中查找用户,而是检查用户的角色成员资格似乎更快 以下是比我问题中的代码执行速度更快的代码:
public static bool ActiveDirectoryGroupMembershipOk(string userid, string groupName)
{
bool membershipOk = false;
using (var pc = new PrincipalContext(ContextType.Machine, "my_pc_name"))
{
using (var p = Principal.FindByIdentity(pc, IdentityType.SamAccountName, userid))
{
// if user account exists, check the group membership
if(p != null)
{
System.Security.Principal.WindowsIdentity wi = new System.Security.Principal.WindowsIdentity(userid);
System.Security.Principal.WindowsPrincipal wp = new System.Security.Principal.WindowsPrincipal(wi);
membershipOk = wp.IsInRole(groupName);
}
}
}
return membershipOk;
}
我找到了一个更好的方法(假设是一个广告域),使用了布朗德先生的部分答案:
public static bool ActiveDirectoryGroupMembershipOk(String userid, String groupname)
{
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userid);
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, groupname);
return user.IsMemberOf(group);
}
根据我的经验,广告总是很慢,所以我倾向于缓存结果。在您的情况下,我将使用一个类全局变量grp,并在每个用户执行该操作时调用FindByidentity。所以这是我的第一个请求,很慢。我刚刚读了另一篇关于查看用户的成员资格而不是组成员的帖子,这可能会更快。但我无法让代码正常工作。