2011/04/09

VB.net 動態變更使用者 switch user dynamically

文章參考: 如何在 ASP.NET 應用程式中實作模擬

VB.net
  1. Public Class Personate
  2.     Private Shared LOGON32_LOGON_INTERACTIVE As Integer = 2
  3.     Private Shared LOGON32_PROVIDER_DEFAULT As Integer = 0
  4.     Private Shared ImpersonationContext As WindowsImpersonationContext
  5.  
  6.     Declare Function LogonUserA Lib "advapi32.dll" (ByVal lpszUsername As String, _
  7.                             ByVal lpszDomain As String, _
  8.                             ByVal lpszPassword As String, _
  9.                             ByVal dwLogonType As Integer, _
  10.                             ByVal dwLogonProvider As Integer, _
  11.                             ByRef phToken As IntPtr) As Integer
  12.  
  13.     Declare Auto Function DuplicateToken Lib "advapi32.dll" ( _
  14.                             ByVal ExistingTokenHandle As IntPtr, _
  15.                             ByVal ImpersonationLevel As Integer, _
  16.                             ByRef DuplicateTokenHandle As IntPtr) As Integer
  17.  
  18.     Declare Auto Function RevertToSelf Lib "advapi32.dll" () As Long
  19.     Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Long
  20.  
  21.     Public Shared Function ImpersonateValidUser(ByVal userName As String, ByVal domain As String, ByVal password As String) As Boolean
  22.  
  23.         Dim tempWindowsIdentity As WindowsIdentity
  24.         Dim token As IntPtr = IntPtr.Zero
  25.         Dim tokenDuplicate As IntPtr = IntPtr.Zero
  26.         ImpersonateValidUser = False
  27.  
  28.         If RevertToSelf() Then
  29.             If LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, token) <> 0 Then
  30.                 If DuplicateToken(token, 2, tokenDuplicate) <> 0 Then
  31.                     tempWindowsIdentity = New WindowsIdentity(tokenDuplicate)
  32.                     ImpersonationContext = tempWindowsIdentity.Impersonate()
  33.                     If Not ImpersonationContext Is Nothing Then
  34.                         ImpersonateValidUser = True
  35.                     End If
  36.                 End If
  37.             End If
  38.         End If
  39.         If Not tokenDuplicate.Equals(IntPtr.Zero) Then
  40.             CloseHandle(tokenDuplicate)
  41.         End If
  42.         If Not token.Equals(IntPtr.Zero) Then
  43.             CloseHandle(token)
  44.         End If
  45.     End Function
  46.  
  47.     Public Shared Sub UndoImpersonation()
  48.         ImpersonationContext.Undo()
  49.     End Sub
  50. End Class

沒有留言: