gpt4 book ai didi

c# - 缓慢的 AD 组成员查找

转载 作者:太空宇宙 更新时间:2023-11-03 15:23:16 24 4
gpt4 key购买 nike

我有一些代码来检查域用户是否是机器管理员组的成员:

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"))

有没有更快的方法来查找成员资格?

不知道重要不重要,userid是Domain User,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;
}

关于c# - 缓慢的 AD 组成员查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36399540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com