facebook  linkedin  Twitter  skype  Rss googlePlus

Active Directory Group Lookup

Dec 30 2003

A method I would like to add to the article "Methods for Active Directory Management" is a way to get the groups the user belongs to. The section titled "Obtaining Group Membership for a User" is a good start to getting your groups, however, it is not fully correct. Just checking the "MemberOf" property will give you the groups the user belongs to but not ALL of the groups. In a corporate environment each user would most likely belong to several groups and have one(1) primary group that they belong to. The property "MemberOf" does not supply the "Primary Group". And in instances when the user has just their "Primary Group" as the only group they belong to, it will show no groups at all. And as you might have guessed, there is little to no information that this is the case. After a lot of digging around and some help on the newsgroups I found a way to get this "Primary Group".

I am not going to go in depth into the code on this one. I have put in many comments to help you through it. The basic idea is to loop through your users or just to query for one user and then use the method Groups below to query for that users information. Groups takes in a single SearchRequest so you can only query one user at a time. However, in my Intranet application we do this for each user that logs in and the speed is very quick. Groups basically loops through the tokenGroups property to retrieve the sid for each group that the user belongs to. This is the only way I know of to get this information at this time. There are a couple of articles on Microsoft's site but the key piece they tend to leave out is how to actually use the Security Identifier (SID) or how to convert the SID.

Public Function Groups(ByVal SearchResult As System.DirectoryServices.SearchResult) As String
    Dim i As Integer
    Dim tmp As String
    Dim groupSid As Object
    Dim sid() As Byte
        Dim de As DirectoryEntry = SearchResult.GetDirectoryEntry
        'pull username and password from web.config file.
        de.Username = Configuration.ConfigurationSettings.AppSettings("User")
        de.Password = Configuration.ConfigurationSettings.AppSettings("Pass")
        de.RefreshCache(New String() {"tokenGroups"})
        'this line is sometimes necessary to get tokenGroups in the property cache...
        'loop through each sid in the tokenGroups
        For Each groupSid In de.Properties("tokenGroups")
            'just another way of doing a ctype.
            sid = DirectCast(groupSid, Byte())
            'set up the groupentry for query
            'ConvertToOctetString is the important part here. This is where the real work is.
            Dim groupEntry As New DirectoryEntry(String.Format("LDAP://", ConvertToOctetString(sid)))
            Dim propcoll As PropertyCollection = groupEntry.Properties
            Dim key As String
            Dim values As Object
            'loop through all of the properties for this record
            For Each key In propcoll.PropertyNames
                'loop through all the values associated with our key
                For Each values In propcoll(key)
                    If LCase(key) = "distinguishedname" Then
                      Dim temp As String = values.ToString
                      If Not InStr(temp, "ImportedExchange") Then
                        Dim atemp() As String = temp.Split(",")
                        tmp &= Replace(atemp(0).ToString, "CN=", ",")
                        If Left(tmp, 1) = "," Then
                            tmp = Mid(tmp, 2)
                        End If
                      End If
                    End If
    Catch ex As Exception
        'process exception
    End Try
    Return tmp
End Property
'overload for lazy programming
Public Overloads Shared Function ConvertToOctetString(ByVal values As Byte()) As String
    Return ConvertToOctetString(values, False, False)
End Function
'overload for lazy programming
Public Overloads Shared Function ConvertToOctetString(ByVal values As Byte(), _
     ByVal isAddBackslash As Boolean) As String
    Return ConvertToOctetString(values, isAddBackslash, False)
End Function
'This is where the work really comes in. This method allows us to convert the sid
'into a usable string that LDAP can use to search for the groups this user belongs to.
Public Overloads Shared Function ConvertToOctetString(ByVal values As Byte(), _
     ByVal isAddBackslash As Boolean, ByVal isUpperCase As Boolean) As String
    Dim iterator As Integer
    Dim builder As System.Text.StringBuilder
    Dim slash As String
    If isAddBackslash Then
        slash = "\"
        slash = String.Empty
    End If
    Dim formatCode As String
    If isUpperCase Then
        formatCode = "X2"
        formatCode = "x2"
    End If
    builder = New System.Text.StringBuilder(values.Length * 2)
    For iterator = 0 To values.Length - 1
    Return builder.ToString()
End Function

So until next time. Cya.

Author Name: Stanley Glass Jr
Bio: Stanley has been programming for about 10 years now. Starting first with Basic. With the introduction of the Internet he found a new desire. A desire to create web pages. Once he created his first he was addicted to it. Html, then javascript, then Perl, on to ASP, and then on to VB and now ending with VB.NET and ASP.NET.

About the Author, Staff

You can write for Santry.com, just email us at [email protected] for more information.

blog comments powered by Disqus


Thank you for visiting our site, before you leave, please visit some of the areas or information you may have missed.

Popular Articles