文章參考: 如何在 ASP.NET 應用程式中實作模擬
VB.net
- Public Class Personate
- Private Shared LOGON32_LOGON_INTERACTIVE As Integer = 2
- Private Shared LOGON32_PROVIDER_DEFAULT As Integer = 0
- Private Shared ImpersonationContext As WindowsImpersonationContext
- 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
- Public Shared 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() 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
- Public Shared Sub UndoImpersonation()
- ImpersonationContext.Undo()
- End Sub
- End Class
沒有留言:
張貼留言