Monday, September 13, 2010

Back to Basic – ASP.NET Runtime Impersonation

Today I got a question from one of the developers at my main customer. The question was how to move an uploaded file from an ASP.NET server to a file server on the network. The answer is of course by impersonating. In this post I’ll explain how you can make ASP.NET impersonation and in more details how to make runtime impersonation.
Impersonation in ASP.NET
When we are doing I/O operations, the operation system makes security checks to understand if the user is authorized to do the operation. The same thing happens when you try to do operations on another machine in your network. Impersonation in ASP.NET occurs when ASP.NET executes code in the context of an authenticated and authorized user. By default, ASP.NET run in the ASPNET account. By using impersonation we can impersonate the ASPNET account to another account that has access to resources which aren’t granted in the internet security permission. One way to impersonate a user is by using the identity element in the web.config. When you use the following code in your web.config, ASP.NET impersonates to the authenticated user or to an anonymous internet user account:
<identity impersonate="true" />
If you want to impersonate to a specific user you can use the following configuration:
<identity impersonate="true" userName="domain\username" password="password" />
Runtime Impersonation
At my customer the previous configuration examples weren’t an option. The second way to impose impersonation is by runtime. This option can be achieved by using the System.Security.Principal and the WindowsIdentity class. The WindowsIdentity class has a method that makes impersonation and returns a WindowsImpersonationContext. The problem with this class is that you need to supply to it an IntPtr which is a security access token of the user that you wish to impersonate to. The solution is to use P/Invoke and call the LogonUser Win32 API.
Read more: Gil Fink on .Net