![](/img/trans.png)
[英]How to validate user credentials if account is a member of AD Protected Users group?
[英]How to test if AD User is a member of a local group
创建新的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);
}
您的示例工作正常,前提是您要向该方法传递UserPrincipalName而不是sAMAccountName,并且contoso仅存在于示例中。
编辑:
试试这个 。 它甚至通过组嵌套检查用户是否是成员:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.