Pages

Thursday, March 15, 2012

Impersonation in ASP.NET

Impersonation is used when we want our ASP.NET application to assume the identity of the local windows account instead of using custom authentication. In order to access any Windows resource on such systems, you have to configure your ASP.NET application to use impersonation. You can use these settings in web.config to turn on the impersonation:



By default ASP.NET runtime does not use impersonation (unless you enable it in web.config), and the code runs in an IIS 6/7 application pool by default (like on Windows 2003 and above). This IIS application pool runs under the NT AUTHORITY\Network Service identity. On an OS with IIS 5, the ASP.NET applications run in a worker process that uses the local ASPNET account identity.

Impersonation can be implemented in two ways:

1. Configured Impersonation: If you use in web.config, you are using built-in impersonation capability in ASP.NET. This will let the user impersonate for the entire duration of the request.

2. Programmatic Impersonation: You can write custom code using Windows API method calls in C#/VB.NET (as .NET does not have a managed wrapper for this) to impersonate a user for the entire duration of a request. If you want more control, such as the ability to impersonate a user for only part of the page request, you have to do the impersonation yourself in your code following this approach. Here you need to use WindowsIdentity.Impersonate() method as shown in this article: http://msdn.microsoft.com/en-us/library/ms998351.aspx

For impersonating users across the domain, we need to use delegation: http://msdn.microsoft.com/en-us/library/ms998355.aspx

Windows authentication and Impersonation are very useful when you are developing a web application for Intra-net systems.But it is less-flexible than using custom authentication.