Friday, June 27, 2008

ASP.NET tactics: Saving files to network shares

Getting a web app to talk to the local file system is hard enough. Getting it to talk to (and certainly to write files) to a networked system is even more difficult.

The initial problem is that the security context that the site runs as is a local one. To complicate things, the security context changes as you progress through the life of an ASP.NET web request. The IIS service typically runs as "Network Service". However, you can set a particular site or virtual directory to run under another user. Furthermore, you can configure ASP.NET to impersonate yet another user. So it can be very difficult to figure out exactly "who" it is that is doing some action against the file system.

As I mentioned, the user context for these processes are local ones. In order to successfully access a network share you'll need to run your site and possibly process(es) as domain accounts in order to get security contexts between machines that will cooperate. Of course, this then also requires both machines being members of the same or trusted domains.

One solution may be to create a virtual directory in the site you are trying to do this in. That virtual directory will point to the network location you wish to save files to. When you set it up you can specify what user to connect as, and in this case you can specify an external user context, such as a local account from the other machine (MACHINENAME\USER). This would likely be a bit more secure that modifying the IIS sites or process. When you save files, you'll just save them to a "local" virtual path such as /mysite/myMappedVirtualDir.

Unfortunately, setting up things like this typically becomes trial-and-error. You have to just keep trying different things until it works. It is understandable that web site technologies adhere to the principle of least privilege, but it often gets in the way of simply getting things done.

No comments: