VB.Net: Impersonation Code

Imports System.Security.Principal

Public Class MainForm

    Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal un As String, ByVal domain As String, ByVal pw As String, ByVal LogonType As Integer, ByVal LogonProvider As Integer, ByRef Token As IntPtr) As Boolean

    Public Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Boolean

    Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        RunImpersonation()

    End Sub

    '' do your work

    Public Sub RunImpersonation()

        Console.WriteLine("> RUNNING...")

        Dim tokenHandle As New IntPtr(0)

        Try

            If LogonUser("<USERNAME>", "<DOMAIN>", "<PASSOWRD>", 2, 0, tokenHandle) Then

                Dim newId As New WindowsIdentity(tokenHandle)

                Using impersonatedUser As WindowsImpersonationContext = newId.Impersonate()

                    '

                    '

                    '  < RUN YOUR IMPERSONATION STUFF HERE

                    '

                    '

                End Using

                CloseHandle(tokenHandle)

            Else

                Console.WriteLine("!! LOG ON FAILED")

            End If

        Catch ex As UnauthorizedAccessException

            Console.WriteLine("!! UNAUTHORIZED: " + ex.Message())

        Catch ex As Exception

            Console.WriteLine("!! EXCEPTION: " + ex.Message())

        End Try

        Console.WriteLine("> COMPLETE")

    End Sub

End Class


Author

This was written by Nate Burchfield