Tom
Tom

Reputation: 4577

Retrieve user information and check if member of a group in active directory using VB.NET

I'm using the following code, which works, to login a user to an application built in VB.NET against active directory.

This code works great but I need to retreive the user's first name, last name, display name and also check if the user is part of a group.

I've tried many forms of adResults.Property("displayname").ToString() and the like but just can't get it to work right.

Anyone have any ideas how to do what I'm looking to do?

Here's the code I'm using now and thanks in advance.

Public Function ValidateActiveDirectoryLogin(ByVal sDomain As String, ByVal sUserName As String, ByVal sPassword As String) As Boolean

    Dim bSuccess As Boolean = False
    Dim adEntry As New System.DirectoryServices.DirectoryEntry("LDAP://" & sDomain, sUserName, sPassword)
    Dim adSearcher As New System.DirectoryServices.DirectorySearcher(adEntry)
    adSearcher.SearchScope = DirectoryServices.SearchScope.OneLevel
    Try
        Dim adResults As System.DirectoryServices.SearchResult = adSearcher.FindOne
        bSuccess = Not (adResults Is Nothing)
    Catch ex As Exception
        bSuccess = False
        MsgBox("Error")
    End Try

    Return bSuccess

End Function 

Upvotes: 1

Views: 11559

Answers (2)

user2696636
user2696636

Reputation: 51

..and to quickly dump the contents of groupnames (from Jeroenh's brillaint answer) into a listbox:

    ListBox1.DataSource = groupnames.ToList()

Upvotes: 0

jeroenh
jeroenh

Reputation: 26792

Look at the System.DirectoryServices.AccountManagemment namespace. The userprincipal object has everything you need and more. Here's an explanation on how to use this API.

EDIT: it's really much simpler to use actually. Have a look at this sample code:

Dim userName = Environment.UserName

' create a domain context
Dim DC = New PrincipalContext(ContextType.Domain)

' find a user in the domain
Dim user = UserPrincipal.FindByIdentity(DC, userName)

' get the user's groups
Dim groups = user.GetGroups()

' get the user's first and last name
Dim firstName = user.GivenName
Dim lastName = user.SurName

' get the distinguishednames for all groups of the user
Dim groupNames = From g in groups Select g.DistinguishedName
' etc...

Upvotes: 4

Related Questions