Option Explicit On
Imports System.Security.Principal
Imports System.Runtime.InteropServices
Public Class index3
Inherits System.Web.UI.Page
Declare Function LogonUserA 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 Integer
Declare Auto Function DuplicateToken Lib "advapi32.dll" (ByVal ExistingTokenHandle As IntPtr, ByVal ImpersonationLevel As Integer, ByRef DuplicateTokenHandle As IntPtr) As Integer
Declare Auto Function RevertToSelf Lib "advapi32.dll" () As Long
Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Long
Private LOGON32_LOGON_INTERACTIVE As Integer = 2
Private LOGON32_PROVIDER_DEFAULT As Integer = 0
Private impersonationContext As WindowsImpersonationContext
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
'Me.txtUsername.Text = "Domain\Username"
'Me.txtPassword.Text = String.Empty
End Sub
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
If impersonateValidUser(Me.txtUsername.Text, Me.txtPassword.Text) Then
'MessageBox.Show("User authenticated sucessfully")
'Insert your code that runs under the security context of a specific user here.
Response.Redirect("index2.aspx")
undoImpersonation()
Else
'MessageBox.Show("Invalid password or user")
'Your impersonation failed. Therefore, include a fail-safe mechanism here.
Response.Redirect("index.aspx")
End If
End Sub
Private Function impersonateValidUser(ByVal userName As String, ByVal password As String) As Boolean
Dim tempWindowsIdentity As WindowsIdentity
Dim token As IntPtr = IntPtr.Zero
Dim tokenDuplicate As IntPtr = IntPtr.Zero
Dim ar() As String
Dim domain As String
impersonateValidUser = False
ar = userName.Split("\")
If UBound(ar) = 0 Then
CloseHandle(token)
Exit Function
Else
domain = ar(0)
userName = ar(1)
End If
If RevertToSelf() Then
If LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, token) <> 0 Then
If DuplicateToken(token, 2, tokenDuplicate) <> 0 Then
tempWindowsIdentity = New WindowsIdentity(tokenDuplicate)
impersonationContext = tempWindowsIdentity.Impersonate()
If Not impersonationContext Is Nothing Then
impersonateValidUser = True
End If
End If
End If
End If
If Not tokenDuplicate.Equals(IntPtr.Zero) Then
CloseHandle(tokenDuplicate)
End If
If Not token.Equals(IntPtr.Zero) Then
CloseHandle(token)
End If
End Function
Private Sub undoImpersonation()
impersonationContext.Undo()
End Sub