Use Programmatic Impersonation

From Guidance Share

Jump to: navigation, search

- J.D. Meier, Alex Mackman, Michael Dunner, Srinath Vasireddy, Ray Escamilla and Anandha Murukan

If you do not want to impersonate an account for the entire request, you can use programmatic impersonation to impersonate for a portion of the request. For example, you want to use the ASP.NET process account to access you application's primary resources and downstream database, but you need to access an alternate resource, such as another remote database or a remote file share, using an alternate identity.

To do this, use IIS to configure the anonymous user account as the trusted alternate identity. Then use the following code to create an impersonation token using the anonymous account only while you execute your remote resource access code:

HttpContext context = HttpContext.Current;
// Get the service provider from the context
IServiceProvider iServiceProvider = context as IServiceProvider;
//Get a Type which represents an HttpContext
Type httpWorkerRequestType = typeof(HttpWorkerRequest);
// Get the HttpWorkerRequest service from the service provider
// NOTE:  When trying to get a HttpWorkerRequest type from the HttpContext
// unmanaged code permission is demanded.
HttpWorkerRequest httpWorkerRequest = 
    iServiceProvider.GetService(httpWorkerRequestType) as HttpWorkerRequest;
// Get the token passed by IIS
IntPtr ptrUserToken = httpWorkerRequest.GetUserToken();
// Create a WindowsIdentity from the token
WindowsIdentity winIdentity = new WindowsIdentity(ptrUserToken);
// Impersonate the user
Response.Write("Before impersonation: " + 
               WindowsIdentity.GetCurrent().Name + "
"); WindowsImpersonationContext impContext = winIdentity.Impersonate(); Response.Write("Impersonating: " + WindowsIdentity.GetCurrent().Name + "
"); // Place resource access code here // Stop impersonating impContext.Undo(); Response.Write( "After Impersonating: " + WindowsIdentity.GetCurrent().Name + "

Note This approach assumes Forms or Passport authentication where your application's virtual directory is configured in IIS to support anonymous access.

If you use this code, use the following <identity> configuration:

<identity impersonate="false" />

Note The code demands the unmanaged code permission SecurityPermission(SecurityPermissionFlag.UnmanagedCode), which is granted only to fully trusted Web applications.


Personal tools