C# 检查当前用户是否是active directory组的成员

C# 检查当前用户是否是active directory组的成员,c#,active-directory,activedirectorymembership,active-directory-group,C#,Active Directory,Activedirectorymembership,Active Directory Group,我需要检查当前用户是否是active directory组的成员。我从获取当前用户开始,如下所示。现在我想知道如何检查此CurrentUser是否在active directory组“CustomGroup”中 请在.NET 3.5或4中尝试以下操作: PrincipalContext infPC = new PrincipalContext(ContextType.Domain, "domain", "login", "password"); UserPrincipal infUP = new

我需要检查当前用户是否是active directory组的成员。我从获取当前用户开始,如下所示。现在我想知道如何检查此CurrentUser是否在active directory组“CustomGroup”中


请在.NET 3.5或4中尝试以下操作:

PrincipalContext infPC = new PrincipalContext(ContextType.Domain, "domain", "login", "password");
UserPrincipal infUP = new UserPrincipal(infPC);
PrincipalSearcher infPS = new PrincipalSearcher();
UserPrincipal foundUP;
GroupPrincipal infGP = new GroupPrincipal(infPC);
GroupPrincipal foundGP;
string CurrentUser = WindowsIdentity.GetCurrent().Name;

infUP.SamAccountName = CurrentUser;
infPS.QueryFilter = infUP;
foundUP = infPS.FindOne();
infGP.Name = "CustomGroup";
infPS.QueryFilter = infGP;
foundGP = infPS.FindOne();
bool ismember = foundUP.IsMemberOf(foundGP);

您可以使用.NET 3.5
System.DirectoryServices.AccountManagement
类。有关详细信息,请参阅MSDN文章。您可以使用以下内容:

string CurrentUser = WindowsIdentity.GetCurrent().Name;

PrincipalContext context = new PrincipalContext(ContextType.Domain, "Domain");
UserPrincipal upUser = UserPrincipal.FindByIdentity(context, CurrentUser);
if(upUser != null)
{
    if (upUser.IsMemberOf(context, IdentityType.SamAccountName, "CustomGroup")) 
    {
        // The user belongs to the group
    }
}

我们知道要在其中搜索当前用户的组。因此,将有任何直接的过程来做到这一点。例如,获取我们要从AD搜索的组,并遍历该组中当前用户的用户?这就是您所写的:“我需要检查当前用户是否是active directory组的成员。”。因此,您需要特定组中的所有用户?这需要用户名和密码,是否有某种方法可以在不知道的情况下检查当前WindowsIdentity是否是组的成员?在不遍历整个组的身份列表的情况下,您必须是您正在查询的域的成员,并且具有特定的用户权限。检查此处或此处。相关问题:upUser.IsInRole(“CustomGroup”)是否应该是upUser.IsMemberOf(“CustomGroup”)?用户是否可以伪造其ID和域?
string CurrentUser = WindowsIdentity.GetCurrent().Name;

PrincipalContext context = new PrincipalContext(ContextType.Domain, "Domain");
UserPrincipal upUser = UserPrincipal.FindByIdentity(context, CurrentUser);
if(upUser != null)
{
    if (upUser.IsMemberOf(context, IdentityType.SamAccountName, "CustomGroup")) 
    {
        // The user belongs to the group
    }
}