I had written some code to make some batch web service requests utilizing delegates. One of the things we ran into was that any new threads created in the ASP.Net application we're being created under the ASPNet account rather then a service account we were using. This caused some problems when we were accessing resources in our application. The ASPNet account didn't have access to those areas.
I was surprised how easy it was to implement impersonation in the code. The solution looked something like this.
In the Page_Load event:
//show who we are running as - should be customuser
System.Security.Principal.WindowsIdentity ident = System.Security.Principal.WindowsIdentity.GetCurrent();
Debug.WriteLine("Page_Load: " + ident.Name);
//retrieve the security token , and cache it in a static variable so it can be used by the other thread.
_intsecuritytoken = System.Security.Principal.WindowsIdentity.GetCurrent().Token;
//create the batch request object and submit a request
AsyncThreadRequest request = new AsyncThreadRequest();
request.Add(new SendReportRequestDelegate(this.FuncToRun));
request.SubmitRequest(true, 20);
The FuncToRun method looked like this:
privatevoid FuncToRun(string testval)
{
//show who we are running as (should be ASPNet)%
System.Security.Principal.WindowsIdentity ident = System.Security.Principal.WindowsIdentity.GetCurrent();
Debug.WriteLine("FuncToRun() - Before Impersonation: " + ident.Name);
//create a new windows identity, with the cached security token from customuser
System.Security.Principal.WindowsIdentity windid = new System.Security.Principal.WindowsIdentity(_intsecuritytoken);
windid.Impersonate();
//show who we are running as - should be customuser
ident = System.Security.Principal.WindowsIdentity.GetCurrent();
Debug.WriteLine("FuncToRun() - Before Impersonation: " + ident.Name);
}
You can get the complete example here:
ImpersonateAsyncThread.csproj.zip (10.14 KB)