Tuesday, July 27, 2010

Impersonation in VB.Net

For a client i had to get some files from a fileshare to process these programmaticly. The language of choice was in this case VB.Net, not my favorite, but the clients wish is the clients wish. The fileshare was located on a machine that was accessible from the normal networkdomain, but the webserver that hosted the web application wasn't part of that domain, so no standard fileshare permissions were available.
We came up with the idea to impersonate the process to the administrator, where we had all the permissions we needed (and more... i know). In the end we wanted to have things configurable, so that we can use another user with the appropriate permissions.

The impersonation uses advapi32.dll's UserLogonA function, you can add it like this into your code:


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

To call this function we need to do the folowing :


Dim token As IntPtr = IntPtr.Zero
Dim loggedOn As Boolean = False
If (LogonUserA(My.Settings.ImpersonateUser, My.Settings.ImpersonateDomain,                         My.Settings.ImpersonatePassword, 9, 0, token) <> 0) Then
                loggedOn = True
End If
If (loggedOn) Then
    Dim newIdentity As WindowsIdentity = New WindowsIdentity(token)
    Dim impersonatedUser As WindowsImpersonationContext = newIdentity.Impersonate()

    << code for impersonated processes goes here >>


    impersonatedUser.Undo()
end if

Pretty straightforward huh! Hence the My.Settings.ImpersonateXXX setting variables, configurable throught the project settings.
It is also important to call the Undo() method of the impersonatedUser variable. When a process throws an exception and this Undo() function isn't called, the process will stay running with the impersonated user permissions, not a good idea!!!

Have fun!

No comments:

Post a Comment