Check if Active Directory user is in a group using VB.net

Within a VB.net program, I want to check if a user is in a group.  The code I have only works if I am joined to the domain (see below). I either need to modify this code to accept credentials (username/password) or I need different code.  I tried many different versions of code (most using LDAP), but can't get anything to work running from a PC that is not yet joined to the domain.
    Public Function IsInGroup2(ByVal objectName As String, groupName As String) As Boolean
        Try
            Return New WindowsPrincipal(New WindowsIdentity(objectName)).IsInRole(groupName)
        Catch ex As Exception
        End Try
        Return False
    End Function

Open in new window

BrianAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

NoahHardware Tester and DebuggerCommented:
Hi there! :)

Perhaps, we can try doing it this way. You might need to replace the GroupName and MyIdentity prameter based on your needs.
Public Function IsInGroup(ByVal GroupName As String) As Boolean
    Dim MyIdentity As System.Security.Principal.WindowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent()
    Dim MyPrincipal As System.Security.Principal.WindowsPrincipal = New System.Security.Principal.WindowsPrincipal(MyIdentity)
    Return MyPrincipal.IsInRole(GroupName)
End Function

Open in new window

BrianAuthor Commented:
Thanks for the input, but it seems that your code requires being joined to the domain if accessing an Active Directory group.  I have the following code, which works, but first you check the user/computer object, then you check all the groups it belongs to, then you iterate thru the groups seeing if the group you want is included. Like I said, it works, but seems like there should be a more concise method.
    Public Function Check_If_Member_Of_AD_Group(ByVal username As String,
    ByVal grouptoCheck As String,
    ByVal domain As String,
    ByVal ADlogin As String,
    ByVal ADpassword As String) _
    As Boolean

         Try

            Dim EntryString As String
            EntryString = "LDAP://" & domain

            Dim myDE As DirectoryEntry

            grouptoCheck = grouptoCheck.ToLower()

            If (ADlogin <> "" AndAlso ADpassword <> "") Then
                myDE = New DirectoryEntry(EntryString, ADlogin, ADpassword)
            Else
                myDE = New DirectoryEntry(EntryString)
            End If

            Dim myDirectorySearcher As New DirectorySearcher(myDE)

            myDirectorySearcher.Filter = "CN=" & username '= "sAMAccountName=" & username
            myDirectorySearcher.PropertiesToLoad.Add("MemberOf")

            Dim myresult As SearchResult = myDirectorySearcher.FindOne()

            Dim NumberOfGroups As Integer
            NumberOfGroups = myresult.Properties("memberOf").Count() - 1

            Dim tempString As String

            While (NumberOfGroups >= 0)
                tempString = myresult.Properties("MemberOf").Item(NumberOfGroups)
                tempString = tempString.Substring(0, tempString.IndexOf(",", 0))
                tempString = tempString.Replace("CN=", "")
                tempString = tempString.ToLower() 'Lets make all letters lowercase
                tempString = tempString.Trim()

                If (grouptoCheck = tempString) Then
                    Return True
                End If

                NumberOfGroups = NumberOfGroups - 1
            End While

            Return False

        Catch ex As Exception
            MessageBox.Show(ex.Message)

        End Try
    End Function

Open in new window

NoahHardware Tester and DebuggerCommented:
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

BrianAuthor Commented:
Noah, in both links, the code does not use authentication, which means it will only work if you are in the domain. I am using this on a device that is not in the domain.
NoahHardware Tester and DebuggerCommented:
I have looked through your code again and I found that it is already very concise. I am not sure how we can make the process shorter, apologies.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
BrianAuthor Commented:
Thanks for the help!
NoahHardware Tester and DebuggerCommented:
You're welcome! Glad I could be of help :)
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.