Impersonate User With

Good Morning everyone. I am tired this morning but happy. Yesterday at work I came up with code to handle both listvew and grid data export issues which I really didn’t want to rewrite over again. So that was good news.

Today I needed to impersonate a user on the network for various reasons. I also demonstrate removing impersonation as this is often forgotten when coding something like this. 

Make it a great day!

Public Class clsIMP

    <DllImport("advapi32.dll")> _
    Private Shared Function LogonUser(ByVal lpszUsername As String, _
                               ByVal lpszDomain As String, _
                               ByVal lpszPassword As String, _
                               ByVal dwLogonType As Integer, _
                               ByVal dwLogonProvider As Integer, _
                               ByRef phToken As Integer) As Boolean
    End Function

    <DllImport("Kernel32.dll")> _
    Private Shared Function GetLastError() As Integer
    End Function

    Private Enum Logon
        Interactive = 2
        Network = 3
        Batch = 4
        Service = 5
        Unlock = 7
        NetworkCleartext = 8
        NewCredentials = 9
    End Enum

    Private Enum Provider
        UserDefault = 0
        WindowsNT35 = 1
        WindowsNT40 = 2
        Windows2000 = 3
    End Enum

    Private NewContext As WindowsImpersonationContext

    <SecurityPermission(SecurityAction.Demand, ControlPrincipal:=True, UnmanagedCode:=True)> _
    Private Shared Function GetWindowsIdentity(ByVal Username As String, _
                                        ByVal Domain As String, _
                                        ByVal Password As String) As WindowsIdentity
        Dim SecurityToken As Integer
        Dim Success As Boolean

        ‘possible to extend program to allow changes to the logon type and provider
        ‘as Ineractive is slower and caches the information compared to the Logon.Network type.
        ‘Though that leaves open the private enumeration information.
        Success = LogonUser(Username, Domain, Password, _
                            Logon.Network, Provider.UserDefault, _

        If Not Success Then
            Throw New System.Exception("Logon Failed. Error: " & GetLastError())
            GetWindowsIdentity = New WindowsIdentity(New IntPtr(SecurityToken))
        End If
    End Function

    Public Function ImpersonateUser(ByVal username As String, _
                    ByVal domain As String, ByVal pwd As String) As Boolean
        Dim NewIdentity As WindowsIdentity
        Dim CurIdentity As WindowsIdentity

            NewIdentity = GetWindowsIdentity(username, domain, pwd)

            If Not NewIdentity Is Nothing Then
                NewContext = NewIdentity.Impersonate
                CurIdentity = WindowsIdentity.GetCurrent

                ‘Debug.WriteLine("Impersonated ID: " & CurIdentity.Name) ‘used for demo/example


                ‘just removing impersonation for demo/example
                ‘would comment out for actual use and call the
                ‘the RemoveImpersonation() method if all went well
                ‘else it gets called upon error event

                CurIdentity = WindowsIdentity.GetCurrent ‘used for demo/example
                ‘Debug.WriteLine("Logon ID: " & CurIdentity.Name) ‘used for demo/example

                ImpersonateUser = True
                Err.Raise(7000, ImpersonateUser)
            End If

        Catch ex As Exception
            ImpersonateUser = False
            Throw New System.Exception("IM Error: " & ex.Message)
        End Try

        Return ImpersonateUser
    End Function

    Public Function RemoveImpersonation() As Boolean
            If Not NewContext Is Nothing Then ‘test if object was ever created/referenced
                NewContext.Undo() ‘if so, then undo impersonation.
                RemoveImpersonation = True
                RemoveImpersonation = True ‘never created object, so no impersonation to revert.
            End If
        Catch ex As Exception ‘something happened during removal, so warn calling app to handle
            RemoveImpersonation = False
            Throw New System.Exception("Removal Failure: " & ex.Message)
        End Try
        Return RemoveImpersonation
    End Function

End Class


Join me on Facebook

Technorati Tags: ,,,,,,,,,,,,,,,,,,,,,,,,,,,,

Windows Live Tags:,.NET Framework,csharp,Impersonate,User,data,impersonation,Logon,Network,NetworkCleartext,Provider,UserDefault,NewContext,WindowsImpersonationContext,SecurityPermission,SecurityAction,Demand,ControlPrincipal,UnmanagedCode,Username,Domain,Password,SecurityToken,System,ImpersonateUser,GetCurrent,demo,RemoveImpersonation,cache

  1. #1 by Simon on May 13, 2009 - 5:28 am

    Just wanted to say thank you very much – the code was really helpful and saved me a lot of digging 🙂

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: