Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying LDAP in VB.NET. I have the user account, and I want a list of groups the user in in

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?

like image 452
YogaMatt Avatar asked Dec 07 '25 00:12

YogaMatt


1 Answers

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:

  • Managing Directory Security Principals in the .NET Framework 3.5
  • MSDN docs on System.DirectoryServices.AccountManagement

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!

like image 124
marc_s Avatar answered Dec 08 '25 21:12

marc_s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!