检查当前用户是否是活动目录组的成员

时间:2012-02-05 20:21:47

标签: c# active-directory activedirectorymembership active-directory-group

我需要检查当前用户是否是活动目录组的成员。我开始将当前用户设置如下。现在我想知道如何检查此CurrentUser是否在活动目录组“CustomGroup”

string CurrentUser = WindowsIdentity.GetCurrent().Name;

2 个答案:

答案 0 :(得分:11)

您可以使用.NET 3.5 System.DirectoryServices.AccountManagement类。有关详细信息,请参阅MSDN文章Managing Directory Security Principals in the .NET Framework 3.5。你可以使用类似的东西:

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
    }
}

答案 1 :(得分:1)

在.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);