1

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

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

2 回答 2

9

This is pretty close to what I use:

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

I haven't tested it for local users though. The logic works in my domain, I just changed PrincipalContext(ContextType.Machine) so it should look at local users now.

Don't forget to add a reference and using statement for System.DirectoryServices.AccountManagement

于 2012-03-20T19:37:50.590 回答
2

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

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 身份验证,它将无法正常工作。

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;
于 2012-03-20T19:50:13.707 回答