Authenticating against Active Directory for Forms Authentication

-->

The code snippet below is used on some private sites (not exposed to the internet) which enables a windows forms web page to allow input of an active directory username and password and authenticate. The machine hosting the web page is a member of the domain (or trusts the domain).

It's probably not ultra secure, but fulfills a purpose. Beware of some word wrap below.

Imports Microsoft.VisualBasic
Imports System.Security.Principal

Namespace UsefulASPNET


Public Class Security
Private Shared LOGON32_LOGON_NETWORK As Integer = 3
Private Shared LOGON32_PROVIDER_DEFAULT As Integer = 0
Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As String, ByVal lpszDomain As String, ByVal lpszPassword As String, ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, ByRef phToken As IntPtr) As Boolean

Public Shared Sub ADlogin(ByVal username As String, ByVal password As String, ByVal cookieEnable As Boolean)
Dim encodedUser As String = HttpUtility.HtmlEncode(username)
Dim myDomain As String = "DOMAIN"

If impersonateValidUser(encodedUser, mydomain, password) Then
FormsAuthentication.RedirectFromLoginPage(encodedUser, cookieEnable)
End If
End Sub

Private Shared Function impersonateValidUser(ByVal userName As String, ByVal domain As String, ByVal password As String) As Boolean
return LogonUser(userName, domain, password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, IntPtr.Zero)
End Function
End Class
End Namespace

On the ASP.NET Web Form, there are two items:
  1. First, the Login Control - all this has is the 'OnAuthenticate' parameter set to 'Login1_Authenticate'
  2. The subroutine itself references the code above:

    Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs)
    UsefulASPNET.Security.CODElogin(Login1.UserName, Login1.Password, Login1.RememberMeSet)
    End Sub