C#

TPL Task and Windows Identity Impersonation - The beauty of Closure

I have created a web application with Windows Authentication and impersonation is enabled as I need the application connect to SQL Server database using Windows Authentication.

I wanted to run a TPL task in the impersonated context, so, I added the following code naively in a action method of one of my controllers

// naive task code

Task.Run(() =>
{
      // Task code here
});

Though, this answer suggests that tasks will run under the same context under which it was created, it wasn't working that way in my case.

The task is created under impersonated context but the task was invoked under the identity configured in application pool which is network service in this case. 

To make this work, I need to invoke the method in the task under impersonated context. The easiest way is to capture the WindowsIdentity and make it available to the task function so it can execute any code under the impersonated context.

The Closure feature helped me to achieve this elegantly.  This means, lambda expressions or lambda functions can access any variables declared in the block where the lambda expressions or lambda functions are defined. So, I created a local variable in my action method and used in the task function to run code under the impersonated context. Here is the sample code

// Task using closure
var currentWindowsIdentity = WindowsIdentity.GetCurrent();
Task.Run(() =>
{

    using (currentWindowsIdentity.Impersonate())
    {
        // Task code here
    }

});
comments powered by Disqus