PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197
Validate Login against Active Directory-VBForums
Page 1 of 2 12 LastLast
Results 1 to 40 of 71

Thread: Validate Login against Active Directory

  1. #1

    Thread Starter
    Super Moderator Wokawidget's Avatar
    Join Date
    Nov 2001
    Location
    Headingly Occupation: Classified
    Posts
    9,633

    Validate Login against Active Directory

    The following function validates a username and password against an active directory.
    VB Code:
    1. Private Function ValidateActiveDirectoryLogin(ByVal Domain As String, ByVal Username As String, ByVal Password As String) As Boolean
    2.         Dim Success As Boolean = False
    3.         Dim Entry As New System.DirectoryServices.DirectoryEntry("LDAP://" & Domain, Username, Password)
    4.         Dim Searcher As New System.DirectoryServices.DirectorySearcher(Entry)
    5.         Searcher.SearchScope = DirectoryServices.SearchScope.OneLevel
    6.         Try
    7.             Dim Results As System.DirectoryServices.SearchResult = Searcher.FindOne
    8.             Success = Not (Results Is Nothing)
    9.         Catch
    10.             Success = False
    11.         End Try
    12.         Return Success
    13.     End Function
    This would be used like:
    VB Code:
    1. If ValidateActiveDirectoryLogin("VBForums", "Woof", "Mouse") Then
    2.    'do something
    3. End If
    Woka

  2. #2
    Junior Member
    Join Date
    Feb 2006
    Location
    Johannesburg, South Africa
    Posts
    30

    Question Re: Validate Login against Active Directory

    Hallo,

    Is it possible to use this code in the Login Form of vb .net?

    Where must I place it?

    Also, can it be used in the Custom Login Authentication ASP code that you have written?

    Apreciate the help.

    Ruaan

  3. #3

  4. #4
    Junior Member
    Join Date
    Feb 2006
    Location
    Johannesburg, South Africa
    Posts
    30

    Re: Validate Login against Active Directory

    Hi, I'm busy taking a look at the login.aspx code and can you tell me where must I place this code

    VB Code:
    1. Private Function ValidateActiveDirectoryLogin(ByVal Domain As String, ByVal Username As String, ByVal Password As String) As Boolean
    2.             Dim Success As Boolean = False
    3.             Dim Entry As New System.DirectoryServices.DirectoryEntry("LDAP://" & Domain, Username, Password)
    4.             Dim Searcher As New System.DirectoryServices.DirectorySearcher(Entry)
    5.             Searcher.SearchScope = DirectoryServices.SearchScope.OneLevel
    6.             Try
    7.                 Dim Results As System.DirectoryServices.SearchResult = Searcher.FindOne
    8.                 Success = Not (Results Is Nothing)
    9.             Catch
    10.                 Success = False
    11.             End Try
    12.             Return Success
    13.         End Function

    Thanks,

    R

  5. #5
    Junior Member
    Join Date
    Feb 2006
    Location
    Johannesburg, South Africa
    Posts
    30

    Re: Validate Login against Active Directory

    Quote Originally Posted by RuaanD
    Hi, I'm busy taking a look at the login.aspx code and can you tell me where must I place this code

    VB Code:
    1. Private Function ValidateActiveDirectoryLogin(ByVal Domain As String, ByVal Username As String, ByVal Password As String) As Boolean
    2.             Dim Success As Boolean = False
    3.             Dim Entry As New System.DirectoryServices.DirectoryEntry("LDAP://" & Domain, Username, Password)
    4.             Dim Searcher As New System.DirectoryServices.DirectorySearcher(Entry)
    5.             Searcher.SearchScope = DirectoryServices.SearchScope.OneLevel
    6.             Try
    7.                 Dim Results As System.DirectoryServices.SearchResult = Searcher.FindOne
    8.                 Success = Not (Results Is Nothing)
    9.             Catch
    10.                 Success = False
    11.             End Try
    12.             Return Success
    13.         End Function

    Thanks,

    R
    Sorry my ASP is very bad

  6. #6

  7. #7
    Addicted Member
    Join Date
    Sep 2006
    Location
    Surabaya, Indonesia
    Posts
    163

    Re: Validate Login against Active Directory

    Hi Wokawidget,

    Your code doesn't work in my project. It always return false. It generate error (the server is not operational) if I remove try-catch and search it directly with this:

    VB Code:
    1. Private Function ValidateActiveDirectoryLogin(ByVal Domain As String, ByVal Username As String, ByVal Password As String) As Boolean
    2.         Dim Success As Boolean = False
    3.         Dim Entry As New System.DirectoryServices.DirectoryEntry("LDAP://" & Domain, Username, Password)
    4.         Dim Searcher As New System.DirectoryServices.DirectorySearcher(Entry)
    5.         Searcher.SearchScope = DirectoryServices.SearchScope.OneLevel
    6.         'Try
    7.         '    Dim Results As System.DirectoryServices.SearchResult = Searcher.FindOne
    8.         '    Success = Not (Results Is Nothing)
    9.         'Catch
    10.         '    Success = False
    11.         'End Try
    12.  
    13.         Dim Results As System.DirectoryServices.SearchResult = Searcher.FindOne
    14.         Success = Not (Results Is Nothing)
    15.         Return Success
    16.     End Function

    My domain server still use WinNT4.0, maybe that happened because WinNT4.0 doesn't support it?

    Thanks

    Michael

  8. #8

  9. #9
    Addicted Member
    Join Date
    Sep 2006
    Location
    Surabaya, Indonesia
    Posts
    163

    Re: Validate Login against Active Directory

    "LDAP://skb_ii"

    skb_ii is the name of my domain.

  10. #10

  11. #11
    Addicted Member
    Join Date
    Sep 2006
    Location
    Surabaya, Indonesia
    Posts
    163

    Re: Validate Login against Active Directory

    Quote Originally Posted by Wokawidget
    Hmmmm try modifying the code so the domain passed to the DirectoryEntry object is like:

    LDAP://skb_ii.com/DC=skb_ii,DC=com

    What happens now?

    Woka

    It still not work. Weren't it supposed to be LDAP://skb_ii.com/DN=skb_ii,DC=com ? I've tried this either, but still no luck. It gives the same error mistake:

    The server is not operational
    at this line :
    VB Code:
    1. Dim Results As System.DirectoryServices.SearchResult = Searcher.FindOne

    And for .com, maybe NT4 didn't support DNS ? (don't have experience in legacy system )

    There's a win2000 server in my company. Maybe I should try join it to test my code.

  12. #12
    Member
    Join Date
    Sep 2005
    Posts
    49

    Re: Validate Login against Active Directory

    If this is an NT4 domain, this may not work. NT4 does not understand this provider

  13. #13

  14. #14
    Addicted Member
    Join Date
    Feb 2007
    Posts
    215

    Re: Validate Login against Active Directory

    Hi guys.

    Does anyone have any ideas or can help me. I have a windows application that i would like to have a login to. I would like the login to check if you are a member of a certain group and then authenticate you to Active Directory by supplying a valid user name and password.

    Maybe i am reading this post wrong but it looks like you are hard coding the user name and password into the code???

    What if my password changes or i want to give more than one person access to use my application?

    Thanks to anyone who can help me

    Cheers
    Thanks

    Craig Wallace

    Active Directory Administrator \ Designer

    SMS 2003 Administrator

    Everything else Networks

  15. #15

    Thread Starter
    Super Moderator Wokawidget's Avatar
    Join Date
    Nov 2001
    Location
    Headingly Occupation: Classified
    Posts
    9,633

    Re: Validate Login against Active Directory

    lol. No, nothing is hard coded.
    The function validates a username and password for a domain, and you can pass in all 3 params.
    I added a demo call, which does have the params "hard coded", but you would just take these values from a UI input...which is simple to do.

    Once you have the user in the search results, you can then browse through it's children and check for the group you want.

    Woka

  16. #16
    Addicted Member
    Join Date
    Feb 2007
    Posts
    215

    Re: Validate Login against Active Directory

    Hi mate and thanks for the reply.

    Ok i am new to vb.net biiiiiiiiiiiiiig time, got kind of comfy with vbscript but realise how lazy a coder it makes you.

    Anyway i am using vb.net 2005 and i have used the built in login form that i would like to use. The code for the form is below, Can you help me blend your code into the code below and to check for AD membership. What i would like to achive is if User Craig Wallace is not a member of say AD Security Group called User Creation then dont let him in, if he is and he supplies the correct login and password then let him in

    Thanks for your help so far.

    Public Class LoginForm

    ' TODO: Insert code to perform custom authentication using the provided username and password
    ' (See http://go.microsoft.com/fwlink/?LinkId=35339).
    ' The custom principal can then be attached to the current thread's principal as follows:
    ' My.User.CurrentPrincipal = CustomPrincipal
    ' where CustomPrincipal is the IPrincipal implementation used to perform authentication.
    ' Subsequently, My.User will return identity information encapsulated in the CustomPrincipal object
    ' such as the username, display name, etc.

    Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
    Me.Close()
    End Sub

    Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
    Me.Close()
    End Sub

    End Class
    Thanks

    Craig Wallace

    Active Directory Administrator \ Designer

    SMS 2003 Administrator

    Everything else Networks

  17. #17

    Thread Starter
    Super Moderator Wokawidget's Avatar
    Join Date
    Nov 2001
    Location
    Headingly Occupation: Classified
    Posts
    9,633

    Re: Validate Login against Active Directory

    Well in the OK_Click event you need to call my function with the username and password, and pass in the domain info.
    But before you do that you much loop through the search results...the user object can be found in the results object.
    Once you have this then you need to loop through it's children and find the group.
    Sorry, I don't have time to write it for you as I am pushed with deadlines

    See what you can find on VBF or google regarding AD search results.

    Woka

  18. #18
    Addicted Member
    Join Date
    Feb 2007
    Posts
    215

    Re: Validate Login against Active Directory

    Hi mate. Thanks very much for the reply. I am soooooooooooooooooo new to vb.net , whats the best way of calling your function. there is no big rush to reply as i know your busy, just when you have a minute

    I am going to do this bit by bit.

    First get it working with just a user name and password then move on to more advanced stuff like AD group

    Thanks again
    Thanks

    Craig Wallace

    Active Directory Administrator \ Designer

    SMS 2003 Administrator

    Everything else Networks

  19. #19

    Thread Starter
    Super Moderator Wokawidget's Avatar
    Join Date
    Nov 2001
    Location
    Headingly Occupation: Classified
    Posts
    9,633

    Re: Validate Login against Active Directory

    Ok. np
    Lets do this in stages.
    So to use the code as it stands now, just validating the user (no group code yet), we would use something like:
    Code:
    Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
       Dim authenticated As Boolean = AuthenticateUser()
       If isAuthenticated Then
          'some code here to open app
          Me.Close()
       Else
          'code here to display incorrect login details
       End If
    End Sub
    
    Private Function AuthenticateUser() As Boolean
       Dim username As String = txtUsername.Text
       Dim password As String = txtPassword.Text
       Dim domain As String = 'this can be in a config file, hard coded (I wouldnt do that), or inputed from the UI
    
       Dim isAuthenticated As Boolean = ValidateActiveDirectoryLogin(username, password, domain)
    
       Return isAuthenticated
    End Function
    Hope this helps.

    Woka

  20. #20
    Addicted Member
    Join Date
    Feb 2007
    Posts
    215

    Re: Validate Login against Active Directory

    Hi mate. Thanks for your time tonight.

    Ok so i have copied your code into the form.

    It may just be a typo but is Dim authenticated not supposed to be Dim isauthenticated

    Code:
    Dim authenticated As Boolean = AuthenticateUser()
       If isAuthenticated Then
    Other small issues that vb.net is throwing up are

    txtUserNames is not declared
    txtPasswords is not declared

    on line

    Dim domain As String = 'this can be in a config file, hard coded (I wouldnt do that), or inputed from the UI

    it is moaning about the = saying expression expected.

    Also it is moaning about Name 'ValidateActiveDirectoryLogin' is not declared.

    Code:
    Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
       Dim authenticated As Boolean = AuthenticateUser()
       If isAuthenticated Then
          'some code here to open app
          Me.Close()
       Else
          'code here to display incorrect login details
       End If
    End Sub
    
    Private Function AuthenticateUser() As Boolean
       Dim username As String = txtUsername.Text
       Dim password As String = txtPassword.Text
       Dim domain As String = 'this can be in a config file, hard coded (I wouldnt do that), or inputed from the UI
    
       Dim isAuthenticated As Boolean = ValidateActiveDirectoryLogin(username, password, domain)
    
       Return isAuthenticated
    End Function
    Thanks

    Craig Wallace

    Active Directory Administrator \ Designer

    SMS 2003 Administrator

    Everything else Networks

  21. #21

    Thread Starter
    Super Moderator Wokawidget's Avatar
    Join Date
    Nov 2001
    Location
    Headingly Occupation: Classified
    Posts
    9,633

    Re: Validate Login against Active Directory

    txtUsername is the name of the text box on screen, as is txtPassword. In your app I don't know what they are called. Replace txtUsername and txtPassword with the name of the controls on your form.

    ValidateActiveDirectoryLogin is the function originally posted in this thread....did you not copy that also?

    The comain name is giving that error because ' means a remark, ie you must replace this bit of code with something.
    Use something like:

    Dim domain As String = "MyDomain.com"

    Bearing in mind your domain is NOT MyDomain.com...it's soemthing else, so replace that with your domain.

    Yea, sorry about typos' Am tired and typed straight into VBF and not a VB.NET editor.

    I may suggest you get a Learn VB.NET in 21 days kind of book...this will seriously benefit you, and you'll be up and running in no tiem at all.

    WOka

  22. #22
    Addicted Member
    Join Date
    Feb 2007
    Posts
    215

    Re: Validate Login against Active Directory

    Thanks for the reply. i am also very tired and going to bed now. i will pick this up tomorrow. thanks for the pointers i will put them right tomorrow.

    Thanks again for your help, it really is helping me learn big time.

    Cheers
    Thanks

    Craig Wallace

    Active Directory Administrator \ Designer

    SMS 2003 Administrator

    Everything else Networks

  23. #23
    Addicted Member
    Join Date
    Feb 2007
    Posts
    215

    Re: Validate Login against Active Directory

    Hi mate.

    Ok picking this back up tonight. I have copied your code as per your posts and have put it into my login form. I am hard coding the domain for the time being. Now when the form loads i am putting the correct login details as thats what i used to login to my laptop but the code always returns in correct login details. I have put a couple of msgbox's in as you will see.

    Any ideas as to why it does not think i am using the right details?

    Thanks for your help.

    Code:
    Public Class AuthenticateWithAD
    
        Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
            Dim isauthenticated As Boolean = AuthenticateUser()
            If isauthenticated Then
                MsgBox("YOU HAVE BEEN AUTHENTICATED")
                Me.Close()
            Else
                MsgBox("YOU HAVE NOT BEEN AUTHENTICATED")
            End If
        End Sub
    
        Private Function ValidateActiveDirectoryLogin(ByVal Domain As String, ByVal Username As String, ByVal Password As String) As Boolean
            Dim Success As Boolean = False
            Dim Entry As New System.DirectoryServices.DirectoryEntry("LDAP://" & Domain, Username, Password)
            Dim Searcher As New System.DirectoryServices.DirectorySearcher(Entry)
            Searcher.SearchScope = DirectoryServices.SearchScope.OneLevel
            Try
                Dim Results As System.DirectoryServices.SearchResult = Searcher.FindOne
                Success = Not (Results Is Nothing)
            Catch
                Success = False
            End Try
            Return Success
        End Function
    
        Private Function AuthenticateUser() As Boolean
            Dim username As String = UsernameTextBox.Text
            Dim password As String = PasswordTextBox.Text
            'Dim domain As String = 'this can be in a config file, hard coded (I wouldnt do that), or inputed from the UI
            Dim domain As String = "WALLACE-UK.COM"
    
            Dim isAuthenticated As Boolean = ValidateActiveDirectoryLogin(username, password, domain)
    
            Return isAuthenticated
        End Function
    
        Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
            Me.Close()
        End Sub
    
    End Class
    Thanks

    Craig Wallace

    Active Directory Administrator \ Designer

    SMS 2003 Administrator

    Everything else Networks

  24. #24

  25. #25
    Addicted Member
    Join Date
    Feb 2007
    Posts
    215

    Re: Validate Login against Active Directory

    Hi mate. Thanks very much for the update. i have changed my code as per your last post. YAY all is working i can now see it is checking with AD for my login which is cool, so thanks very much.

    Ok so on to Part 2. What i now need to work out is that ok so you have the right user name and password but if you are not a member of a Active Directory user group the dont allow login , but if you are and you supply the right user name and password then login.

    Any ideas?

    Thanks in advance
    Thanks

    Craig Wallace

    Active Directory Administrator \ Designer

    SMS 2003 Administrator

    Everything else Networks

  26. #26
    Addicted Member
    Join Date
    Feb 2007
    Posts
    215

    Re: Validate Login against Active Directory

    Hi guys. Ok thought i would share back this code with others. Ok the code is the original code in that it will authenticate a user againt Active Directory.

    The will now also check to see if the user is a member of a certain Active Directory Group. So you now have Group Check and User Name and Password Check.

    Also and it may no use to others but i hve put a bit in here to check if the screen res is 1024 x 768 or above. also it has a progress bar.

    Afew people on here have helped me along the way so cant take full credit for it.

    Anyway here is the code. I hope someone finds it usefull

    Code:
    Imports System.DirectoryServices
    Imports System.Net.Mail
    
    Public Class Authenticate_With_Active_Directory
    
        Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
            Dim isauthenticated As Boolean = AuthenticateUser()
    
            If isauthenticated Then
    
                ProgressBar1.Value = 1
    
                Timer1.Enabled = True
    
    
    
                'MsgBox("YOU HAVE BEEN AUTHENTICATED")
    
                Dim frm As New Main_Menu
                frm.Show()
    
                Me.Close()
    
            Else
    
                ProgressBar1.Value = 1
    
                Timer1.Enabled = True
    
                MessageBox.Show("YOU HAVE NOT BEEN AUTHENTICATED" & _
                    Environment.NewLine & Environment.NewLine & "PLEASE CONTACT THE LONDON SYSTEMS TEAM. THIS LOGON ATTEMPT HAS BEEN RECORDED", "Alert - PLEASE READ , PLEASE READ", MessageBoxButtons.OK, MessageBoxIcon.Information)
    
            End If
    
    
        End Sub
    
        Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    
            ProgressBar1.Value = ProgressBar1.Value + 1
            If ProgressBar1.Value = 50 Then
                Timer1.Enabled = False
                'MsgBox(" progressbar at the end")
            End If
        End Sub
    
    
        Private Function ValidateActiveDirectoryLogin(ByVal Domain As String, ByVal Username As String, ByVal Password As String) As Boolean
            Dim Success As Boolean = False
            Dim Entry As New System.DirectoryServices.DirectoryEntry("LDAP://" & Domain, Username, Password)
            Dim Searcher As New System.DirectoryServices.DirectorySearcher(Entry)
            Searcher.SearchScope = DirectoryServices.SearchScope.OneLevel
            Try
                Dim Results As System.DirectoryServices.SearchResult = Searcher.FindOne
                Success = Not (Results Is Nothing)
            Catch
                Success = False
            End Try
            Return Success
        End Function
    
        Private Function AuthenticateUser() As Boolean
            Dim username As String = UsernameTextBox.Text
            Dim password As String = PasswordTextBox.Text
            'Dim domain As String = 'this can be in a config file, hard coded (I wouldnt do that), or inputed from the UI
            Dim domain As String = "WITHERS.NET"
    
            Dim isAuthenticated As Boolean = ValidateActiveDirectoryLogin(domain, username, password)
    
            Return isAuthenticated
        End Function
    
        Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
            Me.Close()
        End Sub
    
        Private Sub AuthenticateWithAD_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
            Dim screenSize As Rectangle = Screen.PrimaryScreen.Bounds
            If screenSize.Width < 1024 Or screenSize.Height < 768 Then
                MessageBox.Show("Incorrect Screen Size" & _
                Environment.NewLine & Environment.NewLine & "This Application requires a Screen Resolution of 1024 x 768 and above. Please change", "Alert - PLEASE READ , PLEASE READ", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.Close()
            Else
    
            End If
    
            'You grab the current logon username from environment object
            Dim userID As String = Environment.UserName
            'Then pass it into the function like this
            If IsMemberOf(userID, "GROUP NAME YOU WANT TO CHECK") Then
                'MessageBox.Show("Yes")
            Else
                MessageBox.Show("Unauthorised Access, You do not have permission to use this application" & _
                                        Environment.NewLine & Environment.NewLine & "Please contact the London Systems Team", "Alert - UNAUTHORISED ACCESS , UNAUTHORISED ACCESS", MessageBoxButtons.OK, MessageBoxIcon.Information)
    
                Me.Close()
            End If
    
        End Sub
    
        Public Shared Function IsMemberOf(ByVal userName As String, ByVal groupName As String) As Boolean
    
    
            ' Uncomment if using at Withers
    
            Dim answer As Boolean = False
            Dim dirEntry As DirectoryEntry = Nothing
            Dim serverName As String = "SERVER NAME"         'example "server1"
            Dim domainName As String = "DOMAIN NAME"  'example "yahoo", "msn", "google"...
            Dim domain As String = "NET"              'example "com", "org", "net"...
            Dim ldapPath As String = "LDAP://" & serverName & "/DC=" & domainName & ",DC=" & domain
            Dim dirSearcher As DirectorySearcher = Nothing
            Dim result As SearchResult = Nothing
            Try
                'dirEntry = New DirectoryEntry(ldapPath)
                'If you run into security permission issue, try this overload with supplied credentials
                dirEntry = New DirectoryEntry(ldapPath, "USERNAME", "PASSWORD", AuthenticationTypes.Secure)
    
    
                dirSearcher = New DirectorySearcher(dirEntry)
                With dirSearcher
                    .Filter = "(SAMAccountName=" & userName & ")"
                    .PropertiesToLoad.Add("memberOf")
                    result = .FindOne()
                End With
                If Not result Is Nothing Then
                    Dim propertyCount As Integer = result.Properties("memberOf").Count
                    Dim dn As String = String.Empty
                    Dim group As String = String.Empty
                    Dim equalsIndex, commaIndex As Integer
                    Dim propertyCounter As Integer = 0
                    While propertyCounter < propertyCount
                        dn = CType(result.Properties("memberOf").Item(propertyCounter), String)
                        equalsIndex = dn.IndexOf("=", 1)
                        commaIndex = dn.IndexOf(",", 1)
                        If -1 = equalsIndex Then
                            Return False
                        End If
                        group = dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1).ToUpper
                        If group = groupName.ToUpper Then
                            answer = True
                            Exit While
                        End If
                        propertyCounter += 1
                    End While
                End If
            Catch ex As Exception
                Throw New Exception(ex.Message)
            Finally
                'Release unmanaged COM objects
                dirEntry = Nothing
                dirSearcher = Nothing
            End Try
            Return answer
    
        End Function
    
    End Class
    Thanks

    Craig Wallace

    Active Directory Administrator \ Designer

    SMS 2003 Administrator

    Everything else Networks

  27. #27

  28. #28

    Thread Starter
    Super Moderator Wokawidget's Avatar
    Join Date
    Nov 2001
    Location
    Headingly Occupation: Classified
    Posts
    9,633

    Re: Validate Login against Active Directory

    Hi.

    I have cleaned the code up slightly for you. I hope you don't mind.
    I have also combined the Validate and the Check group functions into one function.

    You seemed to be doing something funny with the ldap path, so I simplified this also.

    If you pass a groupname to the function then it validates this and checks if the user is a member, if no groupname is passed then the user is validated for a normal login.

    Hope this helps, and thanks again for posting the code.
    Code:
    Private Function AuthenticateUser() As Boolean
            Dim username As String = "TestUser11@WokasCustomer.com"
            Dim password As String = "Woof123"
            Dim domain As String = "eQuest.local"
    
            Dim isAuthenticated As Boolean = ValidateActiveDirectoryLogin(domain, username, password, "Admins@WokasCustomer.com")
    
            Return isAuthenticated
        End Function
    
    
    
    
        Public Function ValidateActiveDirectoryLogin(ByVal domainName As String, ByVal userName As String, ByVal userPassword As String, ByVal groupName As String) As Boolean
            Dim isValidated As Boolean = False
    
            Try
    
                Dim ldapPath As String = "LDAP://" & domainName
                Dim dirEntry As New DirectoryEntry(ldapPath, userName, userPassword, AuthenticationTypes.Secure)
                Dim dirSearcher As New DirectorySearcher(dirEntry)
    
                dirSearcher.Filter = "(userPrincipalName=" & userName & ")"
                dirSearcher.PropertiesToLoad.Add("memberOf")
    
                Dim result As SearchResult = dirSearcher.FindOne()
    
                If Not result Is Nothing Then
    
                    If groupName.Length = 0 Then
                        isValidated = True
                    Else
                        Dim groupCount As Integer = result.Properties("memberOf").Count
                        Dim isInGroup As Boolean = False
    
                        For index As Integer = 0 To groupCount - 1
                            Dim groupDN As String = result.Properties("memberOf").Item(index)
    
                            Dim equalsIndex As Integer = groupDN.IndexOf("=")
                            Dim commaIndex As Integer = groupDN.IndexOf(",")
    
                            Dim group As String = groupDN.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1).ToLower
                            If group.Equals(groupName.ToLower) Then
                                isInGroup = True
                                Exit For
                            End If
                        Next index
    
                        isValidated = isInGroup
                    End If
                End If
            Catch ex As Exception
                Throw New Exception(ex.Message)
            End Try
    
            Return isValidated
    
        End Function
    Woka

  29. #29
    Addicted Member
    Join Date
    Feb 2007
    Posts
    215

    Re: Validate Login against Active Directory

    Hi mate. No of course i dont mind and its great to see another way of doing it. All about learning

    Thanks again.
    Thanks

    Craig Wallace

    Active Directory Administrator \ Designer

    SMS 2003 Administrator

    Everything else Networks

  30. #30

    Thread Starter
    Super Moderator Wokawidget's Avatar
    Join Date
    Nov 2001
    Location
    Headingly Occupation: Classified
    Posts
    9,633

    Re: Validate Login against Active Directory

    np

    Also, I changed it to search for sAMAccountName to userPrincipalName.

    sAMAccountNames are like eQuest\Wokawidget
    userPrincipalNames are like Wokawidget@eQuest.com

    Most MS apps now use the UPN and not SAMAccountName...except some of thier hosting software, with exchange, as that requires the sAMAccountName to validate a mobile device.

    Woka

  31. #31
    New Member
    Join Date
    Sep 2007
    Posts
    3

    Re: Validate Login against Active Directory

    hi there.

    not that into development, but i find the code very helpful.

    is there a way for the code to be modified and also check for "Bad Login Count"?

    regards.

  32. #32
    New Member
    Join Date
    Sep 2007
    Posts
    3

    Re: Validate Login against Active Directory

    no suggestion? can someone suggest how to get badlogoncount?regards

  33. #33

    Thread Starter
    Super Moderator Wokawidget's Avatar
    Join Date
    Nov 2001
    Location
    Headingly Occupation: Classified
    Posts
    9,633

    Re: Validate Login against Active Directory

    Well if badlogin account is an AD property, then just retrieve this property from the users AD object, which is got during validation process.

    ie
    Code:
    int loginCount = Convert.ToInt32(userADobject.properties["badLogin"].Value.ToString())
    But off the top of my head I dont know what the bad login count ad property is.

    Woka

  34. #34
    New Member
    Join Date
    Sep 2007
    Posts
    3

    Re: Validate Login against Active Directory

    thanks for the reply. i'll try that suggestion.

    we used this:
    Code:
        IntAttempts = objUser.BadLoginCount
    but it's not working as expected.

    regards.

  35. #35
    New Member
    Join Date
    May 2008
    Posts
    3

    Re: Validate Login against Active Directory

    The code works great. Thank you very much.

    is there a way in this function to check the manager property within active directory. for instance:

    Johns manager is Sam

    When John logs in it runs
    Code:
    messagebox.show("Your manager is " &  somthing here)
    thanks again

  36. #36

    Thread Starter
    Super Moderator Wokawidget's Avatar
    Join Date
    Nov 2001
    Location
    Headingly Occupation: Classified
    Posts
    9,633

    Re: Validate Login against Active Directory

    Yes.
    From Post 28, the user object is stored in a variable called "result".
    So to get the manager you would use the following:

    Code:
    Dim managerPath As String.Empty;
    if (result.Properties("managedBy").Count == 1) Then
       Dim managerDN As String = result.Properties("managedBy").Value.ToString()
       managerPath = string.Format("LDAP://{0}", managerDN); 
    End If
    if (managerPath.length > 0) Then
       DirectoryEntry managerObject = new DirectoryEntry(managerPath)
       string managerUPN = managerObject.Properties("userprincipalName").value.ToString()
       string managerDisplayName = managerUPN;
       if (managerObject.Properties("displayName").Count == 1) Then
          managerDisplayName = managerObject.Properties("displayName").value.ToString()
       End If
    End if
    Hope that helps.

    Woka

  37. #37
    New Member
    Join Date
    May 2008
    Posts
    3

    Re: Validate Login against Active Directory

    Is that vb.net code or C# I have not been able to get it to work here is a screen shot of the errors:


  38. #38

    Thread Starter
    Super Moderator Wokawidget's Avatar
    Join Date
    Nov 2001
    Location
    Headingly Occupation: Classified
    Posts
    9,633

    Re: Validate Login against Active Directory

    yes u are right...its a mix of them both

    Doh

    I have been coding in both a lot recently.
    try this:
    Code:
    Dim managerPath As String = String.Empty
    if (result.Properties("managedBy").Count = 1) Then
       Dim managerDN As String = result.Properties("managedBy").Value.ToString()
       managerPath = string.Format("LDAP://{0}", managerDN)
    End If
    if (managerPath.length > 0) Then
       Dim managerObject As DirectoryEntry = new DirectoryEntry(managerPath)
       Dim managerUPN As String= managerObject.Properties("userPrincipalName").value.ToString()
       Dim managerDisplayName As String = managerUPN
       if (managerObject.Properties("displayName").Count = 1) Then
          managerDisplayName = managerObject.Properties("displayName").value.ToString()
       End If
    End if
    Also u need to add:
    Code:
    dirSearcher.PropertiesToLoad.Add("managedBy")

  39. #39
    New Member
    Join Date
    May 2008
    Posts
    3

    Re: Validate Login against Active Directory

    Thank you so much for you time and help. I am a noob at active directory.

    I also still have one error when i get to the

    Code:
    If (result.Properties("managedBy").Count = 1) Then
    the system says "Object referance not set to an instace of an object"

    also the code still shows the following error. If i remove the .value.toString and replace it with .toString it will take the error away but i dont know if it will work here is a picture. thanks again for your help!


  40. #40

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width