检查用户是否是组的成员

时间:2012-03-20 19:02:02

标签: c# asp.net windows login active-directory-group

我有一个代码来检查用户是否是某个组的成员。 我在登录时使用此功能。

请注意我有域用户和本地用户,例如。 testdomain\administratoradministrator

这是我使用的代码:

using (DirectoryEntry groupEntry = new DirectoryEntry("WinNT://./" + userGroupName + ",group"))
{
    foreach (object member in (IEnumerable)groupEntry.Invoke("Members"))
    {
        using (DirectoryEntry memberEntry = new DirectoryEntry(member))
        {
            string completeName = memberEntry.Name;
            DirectoryEntry domainValue = GUIUtility.FindDomain(memberEntry);
            if (domainValue != null)
            {
                completeName = domainValue.Name + "\\" + memberEntry.Name;
            }
            Global.logger.Info("completeName from " + userGroupName + " = " + completeName);
            if (userName.Equals(completeName, StringComparison.InvariantCultureIgnoreCase))
            {
                Global.logger.Debug("IsUserPartOfWindowsGroup returned True with username =" + userName + " , UserGroupName = " + userGroupName);
                return true;
            }
        }
    }
    Global.logger.Debug("IsUserPartOfWindowsGroup returned false for username =" + userName + " , UserGroupName = " + userGroupName);
    return false;
}

此代码有效,但

DirectoryEntry domainValue = GUIUtility.FindDomain(memberEntry);
在我看来,

在探查器中花了很多时间。是否有更好/更快的方法来处理这个问题?

public static DirectoryEntry FindDomain(DirectoryEntry memberEntry)
{
    if (memberEntry.Parent != null)
    {
        if (memberEntry.Parent.SchemaClassName.Equals("domain", StringComparison.InvariantCultureIgnoreCase))
        {
            return memberEntry.Parent;
        }
    }
    return null;
}
另一种方式:

DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, userName, Password);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = "(&(objectClass=user)(|(cn=" + userName + ")(sAMAccountName=" + userName + ")))";
SearchResult result = mySearcher.FindOne();

Global.logger.Info("result == " + result.Path);
foreach (string GroupPath in result.Properties["memberOf"])
{
    if (GroupPath.Contains(adminGroupName))
    {
        Global.logger.Info(compUsrNameForEncryption + "exists in " + adminGroupName);
    }
}

2 个答案:

答案 0 :(得分:8)

这与我使用的非常接近:

public bool IsUserInGroup(string userName, string groupName)
{
    using (var context = new PrincipalContext(ContextType.Machine))
    {
        using (var searcher = new PrincipalSearcher(new UserPrincipal(context) { SamAccountName = userName }))
        {
            using (var user = searcher.FindOne() as UserPrincipal)
            {
                return user != null && user.IsMemberOf(context, IdentityType.SamAccountName, groupName);
            }
        }
    }
}

我还没有为本地用户测试过。逻辑在我的域中工作,我刚刚更改了PrincipalContext(ContextType.Machine)所以现在应该查看本地用户。

不要忘记为System.DirectoryServices.AccountManagement

添加引用和使用语句

答案 1 :(得分:1)

也许我错过了一些东西,但你不能这样做:

if(Page.User.IsInRole("GROUP NAME"))
{
    // user is in group. do your thing
}
else
{
    // user isn't in group
}

当我在ASP.NET上进行Active Directory身份验证时,适用于我。

编辑:这是使用Page.User.IsInRole()描述的link。但是,必须使用Windows身份验证,如果不使用Windows身份验证,则无法正常运行。

EDIT2:由于没有使用Windows身份验证,我就是这样做的:

DirectoryEntry de = new DirectoryEntry(LDAP Address,user,password);
DirectorySearcher searcher = new DirectorySearcher(de);
searcher.Filter = string.Format("(SAMAccountName={0})", user);
SearchResult result = searcher.FindOne();
bool isInGroup = false;
if (result != null)
{
    DirectoryEntry person = result.GetDirectoryEntry();
    PropertyValueCollection groups = person.Properties["memberOf"];
    foreach (string g in groups)
    {
        if(g.Equals(groupName))
        {
           isInGroup = true;
           break;
        }
    }
}
return isInGroup;