Friday, February 17, 2012

Access Remote Server Resources in asp.net

I am writing an asp.net page for work that needs to access files on servers in remote offices, and serve those files to the user who requested it.
The asp.net app knows the path to the file, and in testing a simple command like this works:

Dim FileExists As Boolean = My.Computer.FileSystem.FileExists(filePath)

The problem is that in testing, the user account being used to execute the above code under is my own. But on the production web server, the iis worker process is running under "NETWORK SERVICE" and that account is not on the domain and does not have access to resources...well anywhere.

The solution to this problem was to impersonate a user with domain privileges, and use NTFS permissions to allow that user account access to the resources I need to access.

Using code I found here: http://support.microsoft.com/default.aspx?scid=KB;EN-US;306158#4

I used the code under the "Impersonate a Specific User in Code" section and it worked perfectly!

I basically just copier the code in to my user control with the exception of the code in the form_load sub, and used this where I needed it:

If impersonateValidUser("Username", "Domain", "Password") Then
'Insert your code that runs under the security context of a specific user here.
FileExists = My.Computer.FileSystem.FileExists(filePath) = True
undoImpersonation()
Else
'Your impersonation failed. Therefore, include a fail-safe mechanism here.
Throw New Exception("Unable to access KD files. Security failure.")
End If


Be sure to undo the impersonation after the code you need elevated has executed.

Note: I tried to use the Domain Administrator account for testing, and it seemed to impersonate it, but the code did not execute with elevated privileges. I used a normal domain user account and that did the trick. There must be some failsafe to disallow the use of the Administrator account in this way.

No comments:

Post a Comment