简体   繁体   English

在没有外部安全策略的本地组中搜索本地用户

[英]Search for a Local user in a local group that does not have Foreign Security policy

Basically I found a post that has a solution for a problem we are having in our application and the solution was: 基本上,我发现了一个帖子,该帖子为我们在应用程序中遇到的问题提供了解决方案,而解决方案是:

    private static void listGroupMembers(string groupDistinguishedName, PrincipalContext ctx, List<UserPrincipal> users)
{
    DirectoryEntry group = new DirectoryEntry("LDAP://" + groupDistinguishedName);
    foreach (string dn in group.Properties["member"])
    {

        DirectoryEntry gpMemberEntry = new DirectoryEntry("LDAP://" + dn);
        System.DirectoryServices.PropertyCollection userProps = gpMemberEntry.Properties;

        object[] objCls = (userProps["objectClass"].Value) as object[];

        if (objCls.Contains("group"))
            listGroupMembers(userProps["distinguishedName"].Value as string, ctx, users);

        if (!objCls.Contains("foreignSecurityPrincipal"))
        {                    
            UserPrincipal u = UserPrincipal.FindByIdentity(ctx, IdentityType.DistinguishedName, dn);
            if(u!=null)  // u==null for any other types except users
                users.Add(u);
        }
    }                 
}

However I am trying to search a Local group so if I change the directory entry to say: 但是我试图搜索本地组,所以如果我更改目录条目说:

DirectoryEntry groupEntry =
            new DirectoryEntry(string.Format("WinNT://{0}/{1},group", Environment.MachineName, groupName));

Then it doesn't work and it says that the property doesn't exist. 然后它不起作用,并说该属性不存在。 How can I do the above but for a local group and user? 除了本地组和用户外,我该如何做?

Basically to fix this I ended up doing: 为了解决这个问题,我最终做了:

protected bool IsUserInLocalGroup(string userName, string group)
    {
        using (DirectoryEntry computerEntry = new DirectoryEntry("WinNT://{0},computer".FormatWith(Environment.MachineName)))
        using(DirectoryEntry groupEntry = computerEntry.Children.Find(group, "Group"))
        {
            foreach (object o in (IEnumerable)groupEntry.Invoke("Members"))
            {
                using (DirectoryEntry entry = new DirectoryEntry(o))
                {
                    if (entry.SchemaClassName.Equals("User", StringComparison.OrdinalIgnoreCase) && entry.Name.Equals(userName, StringComparison.OrdinalIgnoreCase))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM