在VB.NET中查询LDAP。我有用户帐户,我想要一个用户所在的组列表

时间:2013-07-08 15:48:15

标签: vb.net active-directory ldap active-directory-group directorysearcher

我知道SAMAccountName,现在想要填充一个组列表,其中的条目反映了整个目录中该用户的组成员身份。这是我的开始,但我很难过:

        Dim path As String = WebConfigurationManager.AppSettings("ldapPath")
        Dim entry As New DirectoryEntry(path)
        Dim search As DirectorySearcher = New DirectorySearcher(entry)
        Dim groupList As StringBuilder = New StringBuilder()
        search.Filter = "(SAMAccountName=" & _thisUser.UserName & ")"
        search.PropertiesToLoad.Add("memberOf")
        'search.SearchScope = SearchScope.Subtree

        For Each res As SearchResult In search.FindAll
        Next  ''Just doing this so I can look at "res" objects in debug

我不知道如何遍历这个。请问,有什么指示?

2 个答案:

答案 0 :(得分:4)

如果您使用的是.NET 3.5及更高版本,则应查看System.DirectoryServices.AccountManagement(S.DS.AM)命名空间。在这里阅读所有相关内容:

基本上,您可以定义域上下文并轻松在AD中查找用户和/或组:

// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
    // find a user
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, yourSamAccountName);

   if(user != null)
   {
        var groups = user.GetGroups();

        // iterate over groups or do whatever else you need to do....
   }
}

新的S.DS.AM让您可以轻松地与AD中的用户和群组一起玩!

答案 1 :(得分:0)

memberOf属性具有distinguished name语法,并且是该用户所属的组的DN。换句话说,如果条目具有memberOf属性,并且该属性的值为有效组DN,则该用户已经是该组的成员。