检查用户是否是组的成员

本文关键字:成员 是否是 用户 检查 | 更新日期: 2023-09-27 18:28:38

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

请注意,我有一个域用户和本地用户,例如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);
    }
}

检查用户是否是组的成员

这与我使用的非常接近

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添加引用和使用语句

也许我错过了什么,但你不能就这么做吗:

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()的链接。必须使用Windows身份验证,但如果不使用Windows身份证明,它将无法正常工作。

编辑2:由于没有使用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;