Hi,
use this code to authenticate a user on a windows domain.
VB Code:
Option Strict On Option Explicit On Imports System Imports System.Security.Principal 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 Function impersonateValidUser(ByVal userName As String, ByVal domain As String, ByVal password As String) As Boolean Dim tempWindowsIdentity As WindowsIdentity Dim token As IntPtr = IntPtr.Zero Dim tokenDuplicate As IntPtr = IntPtr.Zero impersonateValidUser = False If RevertToSelf() <> 0 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 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click If impersonateValidUser(Me.TextBox1.Text, SystemInformation.UserDomainName(), Me.TextBox2.Text) Then Console.WriteLine("Autenticated") 'Insert your code that runs under the security context of a specific user here. undoImpersonation() Else MessageBox.Show("Invalid Password") Exit Sub End If End Sub
Regards
Jorge
