Imports System.Runtime.InteropServices
Imports System.Security.Principal
Imports System.Security
Namespace Atomic.Security
Public Class Windows
Private Sub New()
End Sub
'Private Const NetworkLogon As Integer = 3
'Private Const DefaultLogonProvider As Integer = 0
_
Shared Function LogonUser(ByVal userName As String, _
ByVal userDomain As String, ByVal userPassword As String, _
ByVal logonType As Integer, ByVal logonProvider As Integer, _
ByRef token As Integer) As Boolean
End Function
Public Shared Function Impersonate(ByVal userDomain As String, _
ByVal userName As String, ByVal userPassword As String) _
As WindowsImpersonationContext
Dim token As Integer
If LogonUser(userName, userDomain, userPassword, 3, 0, token) Then
Dim impersonatedToken As New IntPtr(token)
Dim newIdentity As New WindowsIdentity(impersonatedToken)
Dim impersonationContext As WindowsImpersonationContext = _
newIdentity.Impersonate()
Return impersonationContext
End If
Return Nothing
End Function
End Class
End Namespace
To use this code you could do the following:
Dim wc As WindowsImpersonationContext = Windows.Impersonate("FoxAtomic", "dfox", "password")
'Impersonate the user here to open a file
File.Create("c:\windows\dan.txt")
wc.Undo() ' Done
No comments:
Post a Comment