Imports System.Security.Principal
Imports System.Security.Permissions
Public Class Form2
Declare Function LogonUser Lib "ADVAPI32.dll" Alias "LogonUserA" ( _
ByVal lpszUsername As String, _
ByVal lpszDomain As String, _
ByVal lpszPassword As String, _
ByVal dwLogonType As LogonType, _
ByVal dwLogonProvider As LogonProvider, _
ByRef phToken As IntPtr) As Int32
Declare Function GetLastError Lib "kernel32.dll" () As Int32
Public Enum LogonType As Integer
LOGON32_LOGON_INTERACTIVE = 2
LOGON32_LOGON_NETWORK = 3
LOGON32_LOGON_BATCH = 4
LOGON32_LOGON_SERVICE = 5
LOGON32_LOGON_UNLOCK = 7
LOGON32_LOGON_NETWORK_CLEARTEXT = 8
LOGON32_LOGON_NEW_CREDENTIALS = 9
End Enum
Public Enum LogonProvider As Integer
LOGON32_PROVIDER_DEFAULT = 0
End Enum
<SecurityPermissionAttribute(SecurityAction.Demand, ControlPrincipal:=True, UnmanagedCode:=True)> _
Private Shared Function GetWindowsIdentity(ByVal UserName As String, _
ByVal Domain As String, ByVal Password As String) As WindowsIdentity
Dim SecurityToken As IntPtr
Dim Success As Boolean = LogonUser(UserName, Domain, Password, _
LogonType.LOGON32_LOGON_NETWORK_CLEARTEXT, _
LogonProvider.LOGON32_PROVIDER_DEFAULT, SecurityToken)
If Not Success Then
Throw New System.Exception("Logon Failed. Error: " & GetLastError())
End If
Return New WindowsIdentity(SecurityToken)
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MsgBox(WindowsIdentity.GetCurrent.Name)
Dim wi As WindowsIdentity = GetWindowsIdentity("testuser", "", "test")
Dim ic As WindowsImpersonationContext = wi.Impersonate()
MsgBox(WindowsIdentity.GetCurrent.Name)
ic.Undo()
MsgBox(WindowsIdentity.GetCurrent.Name)
End Sub
End Class