ASP.NET Read Files from a Password Protected Network Share

asp.netnetworkingshare

I have an ASP.NET website on a Windows 2003 Server, that needs to access files from a network share. The network share is password protected and needs a username and password to be provided.

I use forms based authentication on the website and not windows based.

So my problem is, when I try to read any file from the networkshare using the code below, it throws access denied
DirectoryInfo networkShare = new DirectoryInfo("\\TestServer\Share");

So I tried using Impersonate by providing the username and password of the network share to the impersonate function call, however the call obviously fails since that username does not exists on the ASP.NET webserver. So then I passed the username and password of a login that does exist on the webserver, so this time the impersonate call works however it still can not access the network share 'cuz the network share username and password are different.

So finally, I created the exact same username/password on the webserver which matches the network share. This time impersonate function call works and so does network share. I'm able to successfully read from the share.

So my question is, is there a way I can read the network share without adding the username in the webserver. 'Cuz everytime the network share login changes, I'll have to again make a new username in the webserver too. Which is not ideal.

Any ideas?

Best Answer

The "right" way to do this is to run the webserver's AppPool as the identity that can access the share. That way, the only credential storage is done securely in the IIS config (rather than in your code or in readable config files). Putting the webserver and fileserver in the same Windows domain (or different domains with trust) is the easiest way, but the "same username/password" thing should work there as well.

If you don't care about putting usernames/passwords in your code or config, you can P/Invoke to WNetAddConnection2 and pass the username/password- then you should be able to access the share. This doesn't require the webserver to have a matching account, but you really should secure the password (look into System.Security.Cryptography.ProtectedData for encrypted registry storage).