Run threads and async handlers under the same impersonated identity as the website

When you run a background thread or async handler in asp.net, the thread will not run with the same identity specified in the impersonate tag of the web.config.  You can easily get around this by grabbing the identity before the thread starts and either storing it in a variable or passing it to the thread as part of the ParameterizedThreadStart delegate.

 

Here are some code chunks to copy and paste:

WindowsIdentity appID= System.Security.Principal.WindowsIdentity.GetCurrent();

ParameterizedThreadStart ts = new ParameterizedThreadStart(RunSyncThread);
Thread workerThread = new Thread(ts);
workerThread.Start(appID);

Now, from the thread itself, you only need to take the Identity object and impersonate using it.

WindowsImpersonationContext wi = appID.Impersonate();
 

Your thread will now operate under the proper identity!

more later – joel

No Comments