Question

I know the SAMAccountName, and now want to populate a list of groups with entries that reflect this user's group membership across the whole directory. Here's my start, but I'm stumped:

        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

I've no idea how to traverse this. Please, any pointers?

Was it helpful?

Solution

If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

Basically, you can define a domain context and easily find users and/or groups in 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....
   }
}

The new S.DS.AM makes it really easy to play around with users and groups in AD!

OTHER TIPS

The memberOf attribute has distinguished name syntax, and is the DN of a group of which that user is a member. In other words, if the entry has a memberOf attribute, and that attribute has a value that is a valid group DN, then the user is already a member of that group.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top