从LDAP查询用户组

如何从C#.NET for ASP中的LDAP活动目录中获取用户组用户。在我的场景中,我想将用户名传递给从LDAP Active目录查询的方法,并告诉我我的用户是此用户组的成员。请帮帮我     
已邀请:
如果您使用的是.NET 3.5或更高版本,则还可以使用新的
System.DirectoryServices.AccountManagement
(S.DS.AM)命名空间。 有了这个,你可以做类似的事情:
// create context for domain
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find the user
UserPrincipal up = UserPrincipal.FindByIdentity(ctx, "YourUserName");

if(up != null)
{
    // get groups for that user
    var authGroups = up.GetAuthorizationGroups();
}
阅读有关新S.DS.AM名称空间的更多信息: 管理.NET Framework 3.5中的目录安全性主体     
查看使用System.DirectoryServices命名空间。您可以使用DirectorySearcher查找用户。获得该用户的DirectoryEntry对象后,执行以下操作:
public List<string> GetMemberOf(DirectoryEntry de)
{
  List<string> memberof = new List<string>();

  foreach (object oMember in de.Properties["memberOf"])
  {
    memberof.Add(oMember.ToString());
  }

  return memberof;
}
这将返回一个字符串列表,这些字符串是用户所属的组名。 当然,您可以进一步优化它以包含DirectorySearcher代码,这样您就可以将函数传递给samAccountName。     
试试这个...
public override string[] GetRolesForUser(string username)
    {
    var allRoles = new List<string>();
    var root = new DirectoryEntry(WebConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString,
                                    ConnectionUsername,
                                    ConnectionPassword);

    var searcher = new DirectorySearcher(root,
                                        string.Format(CultureInfo.InvariantCulture, "(&(objectClass=user)({0}={1}))",
                                                                                    AttributeMapUsername,
                                                                                    username));

    searcher.PropertiesToLoad.Add("memberOf");
    SearchResult result = searcher.FindOne();
    if (result != null && !string.IsNullOrEmpty(result.Path))
    {
        DirectoryEntry user = result.GetDirectoryEntry();
        PropertyValueCollection groups = user.Properties["memberOf"];
        foreach (string path in groups)
        {
            string[] parts = path.Split(',');
            if (parts.Length > 0)
            {
                foreach (string part in parts)
                {
                    string[] p = part.Split('=');
                    if (p[0].Equals("cn", StringComparison.OrdinalIgnoreCase))
                    {
                        allRoles.Add(p[1]);
                    }
                }
            }
        }
    }
    return allRoles.ToArray();
}
    
使用DirectorySearcher类来执行ldap查询。 以供参考: http://www.codeproject.com/KB/system/QueryADwithDotNet.aspx     
我需要一种验证用户和检查它们是否在特定用户组中的方法。我通过推送用户名和密码并将“memberOf”属性加载到“search”实例中来实现。以下示例将显示该特定用户名的所有组。 'catch'语句将捕获错误的用户名或密码。
DirectoryEntry entry = new DirectoryEntry("LDAP://xxxxxxxx/OU=xxxxxxx,DC=xxxxxx,DC=xxxxx,DC=xxxxxx", strLdapUserName, strLdapPassword);

    try
    {
    //the object is needed to fire off the ldap connection
    object obj = entry.NativeObject;

    DirectorySearcher search = new DirectorySearcher(entry);
    search.Filter = "(SAMAccountName=" + strLdapUserName + ")";
    search.PropertiesToLoad.Add("memberOf");
    SearchResult result = search.FindOne();
    string filterAttribute = (String)result.Properties["cn"][0];

    foreach(string groupMemberShipName in result.Properties["memberOf"])
    {
        Console.WriteLine("Member of - {0}", groupMemberShipName);
    }

    }
    catch (Exception ex)
    {
    //failed to authenticate
    throw new Exception(ex.ToString());
    }
希望这可以帮助。 (记得引用System.DirectoryServices)     
我认为上面列出的大多数方法都可行,但我建议添加代码以确保您的代码可以“检测嵌套组成员资格中的循环循环”,如果找到,则打破您选择的脚本可能进入的任何无限循环。     

要回复问题请先登录注册