Impersonate Remote User – Visual Basic 2010 – Framework 4

Di seguito del codice Visual Basic che illustra come eseguire l’impersonate di un utente remoto per accedere ad uno share e leggere il contenuto di una cartella.

Con questa modalità si possono utilizzare le credenziali dell’utente presente sulla macchina remota.

Attenzione che la funzione LogonUserA tramite il parametro LOGON32_LOGON_NEW_CREDENTIALS, permette di accedere alla risorsa remota tramite l’impersonate, ma funziona solo per l’accesso alle risorse di rete.

Imports System.IO
Imports System.Security
Imports System.Security.Principal

Public Class Form1

    Dim LOGON32_LOGON_NEW_CREDENTIALS As Integer = 9
    Dim LOGON32_PROVIDER_DEFAULT As Integer = 0
    
    Declare Function LogonUserA Lib "advapi32.dll" (ByVal lpxzUsername 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
    
    Dim impersonationContext As WindowsImpersonationContext

    Private Sub bnTestListFile_Click(sender As System.Object, e As System.EventArgs) Handles bnTestListFile.Click

        Try
            'Impersonate
            If impersonateValidUser("<nomeutente>", "<dominio/nomehost>", "<password>") Then

                'Codice eseguito con le nuove credenziali
                Dim di As New IO.DirectoryInfo("\\nomePC\sharefolder")
                Dim diar1 As IO.FileInfo() = di.GetFiles()
                Dim dra As IO.FileInfo
                For Each dra In diar1
                    ListBox1.Items.Add(dra)
                Next
                'Ripristino credenziali precedenti
                undoImpersonation()
                MsgBox("Success")
            Else
                MsgBox("Failure")
            End If
        Catch ex As Exception
            MsgBox("Error:" & ex.Message & vbCrLf & Principal.WindowsIdentity.GetCurrent.Name)
        End Try

    End Sub

    'Funzione che esegue l'impersonate di un determinato utente
    Private 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_NEW_CREDENTIALS, 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

    'Funzione che annulla l'impersonate e ripristina l'utente corrente
    Private Sub undoImpersonation()
        impersonationContext.Undo()
    End Sub


End Class

Per maggiori informazioni:
http://support.microsoft.com/kb/306158
http://msdn.microsoft.com/en-us/library/windows/desktop/aa378184(v=vs.85).aspx

This entry was posted in Microsoft .NET Visual Basic, Programming Languages. Bookmark the permalink.