Site Search:
Sign in | Join | Help
4Penny.net

ASP.NET

Notes, Tricks and Tips on ASP.NET Coding

Querying Active Directory From .NET

On a recent project, I needed to query Active Directory to get a list of people in a specific group.  I didn't find much sample code for this so i thought i'd post what I figured out. 

This function returns the users in the current active directory group.  It does this by getting a list of all the users and checking what group they are in.

The group itself lists what users are in it, but it stores the display name not the user name.

This code may not be scalable, but it worked for us. I read, but haven't tested, that ldap queries limit to 1000 results so this may be a problem if there are more than 1000 users.

 

Imports System
Imports System.Web.Security
Imports System.Collections.Generic
Imports System.DirectoryServices



....


 Public Function GetUsersInRole(ByVal roleName As String) As String()


    Dim entry As New DirectoryEntry("LDAP://domainControllerName/DC=domain,DC=com")
    Dim search As New DirectorySearcher(entry)


    'Selecting the properties to load is for performance.
    search.PropertiesToLoad.Add("UserPrincipalName")
    search.PropertiesToLoad.Add("MemberOf")



    Dim users As New List(Of String)


    Dim result As SearchResultCollection = search.FindAll()


    For Each i As SearchResult In result
        Dim props_col As ResultPropertyCollection
        props_col = i.Properties


        'not all of the results are users.  We only want properties that
        'have a username.  This could probably be fixed with a better 
        'initial query, but it works :)
        If props_col.Item("UserPrincipalName").Count > 0 Then


            'get the username
            'It looks like corey@devshed.local
            'We want everything before the @
            Dim username As String = CType(props_col.Item("UserPrincipalName")(0), String).Split("@")(0)
            Dim usergroups As New List(Of String)


            For Each j In props_col.Item("MemberOf")
                'the property looks like 
                'CN=Domain Admins,CN=Users,DC=devshed,DC=local
                'We want to get just what the first CN is, Domain Admins


                usergroups.Add(j.ToString().Split(",")(0).Substring(3))


            Next


            'if the user is a member of the group, add them to the list
            If usergroups.Contains(roleName) Then
                users.Add(username)
            End If


        End If


    Next


    Return users.ToArray()


 


End Function

Comments

No Comments