February 2008 Entries
ASP.NET Security Context

Figuring out the credentials passed by an ASP.NET application hosted on an IIS server to a remote resource is a common question in the community forums. Typical errors associated with this type of enquiry are "Acces to the path C:\YourFolder is denied" or "Login failed for user [username]. Reason: Not associated with a trusted SQL Server connection". The context under which a thread accessing a remote resource is running under is a function of two settings, the identity element of the web.config file and the authentication settings in IIS.  With the combination of these options, one can arrive at any of the below security contexts.

Temporarily Impersonating

For security reasons, you may have a scenario where you want to impersonate only for a limited section of code and then return back to the application pool identity. To achieve this, Anonymous access must be disabled, else you will get the error "An anonymous identity cannot perform impersonation". Next, impersonation must not be enabled in your web.config since we are impersonating programmatically. With these two conditions met, your code should look like this

//Code executed here will run under context of the app pool

System.Security.Principal.WindowsImpersonationContext context;
Context = ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();

//Code executed here will run under the context of the client account


//Code executed here will run under the context of the app pool

Temporarily Reverting To The App Pool Identity

What if you want to do just the opposite? That is, temporarily disable impersonation, run a piece of code under the app pool identity, and then return to impersonating the client. To do this, you will want to enable impersonation in the web.config like so

<identity impersonate="true" />

Also, you will want to disable anonymous access on the IIS server, othersise, with impersonation enabled, the application will run under the identity of the anonymous user (see above diagram). Next, to achieve programmatic reversion to the app pool you will want to write code that looks like this

//Code executed here will run under the context of the client account

System.Security.Principal.WindowsImpersonationContext context;
context = WindowsIdentity.Impersonate(System.IntPtr.Zero)

//Code executed here will run under the context of the app pool




If you are still having trouble figuring out what credentials a thread is running under, Microsoft has a tool called Process Monitor (a combination of the Sysinternals Filemon and Regmon utilities) that reports process information and events at an incredibly granular level.

posted @ Saturday, February 09, 2008 5:31 PM | Feedback (0)