Imports System.Security.Principal
Imports System.Security.Permissions
Private Shared Function LogonUser(ByVal lpszUsername As String, _
ByVal lpszDomain As String, ByVal lpszPassword As String, _
ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _
ByRef phToken As Integer) As Boolean
End Function
<DllImport("Kernel32.dll")> _
Private Shared Function GetLastError() As Integer
End Function
<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 Integer
Dim Success As Boolean
Success = LogonUser(UserName, Domain, Password, Logon.NetworkCleartext, Provider.Windows2000, SecurityToken)
If Not Success Then
Throw New System.Exception("Logon Failed. Error: " & _
GetLastError())
End If
GetWindowsIdentity = New WindowsIdentity(New _
IntPtr(SecurityToken))
End Function
Public Shared Sub ImpersonateAdministrator(ByVal Impersonate As Boolean)
Dim newidentity As WindowsIdentity
Dim oldidentity As WindowsIdentity
Dim Username, Domain, Password As String
If Impersonate = True Then
newidentity = GetWindowsIdentity("user", "domainname", "password")
NewContext = newidentity.Impersonate
Else
NewContext.Undo()
End If
End Sub