Some web applications need to impersonate a user account for one reason or another. This is done from web.config and could look like this:

<identity impersonate="true" />

Threading


The impersonation works fine, but if you create new threads manually you would lose the impersonation if you don’t move it along to the new thread. This gave me a severe headache before I figured out how to pass the impersonation to the newly created thread.  

What you need to do, is to pass the WindowsIdentity object to the new thread and from there impersonate again manually.  Here is an example of how to do it using the ThreadPool:

public void StartAsyncCall()
{
  System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
  ThreadPool.QueueUserWorkItem(RunAsyncCall, identity);
}

private void RunAsyncCall(object stateInfo)
{
  System.Security.Principal.WindowsIdentity identity = (System.Security.Principal.WindowsIdentity)stateInfo;
  identity.Impersonate();

  DoSomething();
}

As you can see, it is pretty simple once you know how.

Comments


Comments are closed