Problem: Uploading a document to a location not in Web Project/Web Server
Recently, I was tasked to write and ASP.NET page to upload files to a NAS. Everything worked fine as long as I was uploading to a folder in my project, but, in the release version, the file would be uploaded to a NAS. That was when NTFS security came into play. As soon as I tried to upload to the NAS, I got a misleading message: System.IO.DirectoryNotFoundException. It dawned on me that something was flakey here because the endpoint was obviously there. Ah, that was the clue. After a brief Google search, I confirmed that the account associated with the ASP.NET worker process (in my case, the default (local) ASPNET user) did not have permissions to the NAS.
The two choices that I had to make was a) Change the ASP.NET account, b) impersonate an account. I was leary of chaning the ASP.NET account on the machine. We have several applications on that server, and I did not want to be responsible for any doors that might be opened by elevating the account. So, I decided to impersonate. In addition, I did not want use impersonation in the entire site, just on the pages that would perform the uploading/downloading.
To do this, I started by partioning my application so that my Upload.aspx page was in a sub-directory. I did this so that I could then add a web.config to this directory and change the impersonation tags.
Next, I edited the web.config file in the Attachments sub directory so that I only had the impersonation tags. Originally, I was going to hardcode the user name and password into the file, but, decided that it would be better to err on securing those values. I used a utility called Aspnet SetReg to encrypt the credentials and store them in the registry. Once that was completed, my web.cofig section looked like this:
<?
xml version="1.0" encoding="utf-8" ?>
<configuration>
<location path="Upload.aspx">
<system.web>
<identity impersonate="true"
userName="registry:HKLM\Software\ASPNetApp\Identity\ASPNET_SETREG,userName"
password="registry:HKLM\Software\ASPNetApp\Identity\ASPNET_SETREG,password"
/>
</system.web>
</location>
</configuration>
I also decided to use the Location path to further specify that only the Upload.aspx file in this directory should perform the upload. Once I compiled this, I found the one thing that I did not like about the solution. I had to give permissions to this account to my Temporary ASP.NET Files folder (located at %windir%\Microsoft.NET\Framework\v1.1.4322\Temporary ASP.NET Files). Once finished, I was able to upload my files to the NAS by using the “out of the box” features of ASP.NET.
Cheers!