Helpful Information
 
 
Category: ASP.NET
AsyncCallback & impersonate?

I’m trying to call a web service method from an ASP.NET application that uses Forms Authentication and impersonation for the SQL Server call:



// The method that calls a long running web service
public void RunCompliance(int a, string b, CookieContainer cookieContainer)
{
...

CrimHelper crim = new CrimHelper(cookieContainer);

// The async call
CreateCrimOrdersDelegate dc = new CreateCrimOrdersDelegate(crim.CreateCrimOrders);
AsyncCallback cb = new AsyncCallback(this.GetComplianceResultOnCallback);
IAsyncResult ar = dc.BeginInvoke(a, b, cb, null);

...
}



// The callback method
private void GetComplianceResultOnCallback(IAsyncResult ar)
{
CrimComplianceResultInfo complianceResult = new CrimComplianceResultInfo();

CreateCrimOrdersDelegate del = (CreateCrimOrdersDelegate)
((AsyncResult)ar).AsyncDelegate;

// Get the compliance results
complianceResult = del.EndInvoke(ar);

// Get the Term Sheet that this callback belongs to
TermSheetInfo termSheet = GetTermSheet(complianceResult.TermSheetId);

...
}




// The delegate
private delegate CrimComplianceResultInfo CreateCrimOrdersDelegate(int a, string b);



Section of the web.config:
<system.web>
<identity impersonate="true"
userName="<DOMAIN>\<sysuser>"
password="<password>" />

...
</system.web>

My problem is that the line "termSheet = GetTermSheet(complianceResult.TermSheetId);" in the GetComplianceResultOnCallback method calls the database with the wrong WindowsIdentity (i.e. not the user id specified in the identity section of the configuration file.

The database call returns the following error message:
Login failed for user '(null)'. Reason: Not associated with a trusted SQL Server connection

Some debugging shows that the thread in the callback method has a WindowsIdentity of "NT AUTHORITY\NETWORK SERVICE".

Question:
How can I pass the WindowsIdentity of the existing thread (the oen using the impersonate user id) to the new thread that’s created in the IAsyncResult ar = dc.BeginInvoke(a, b, cb, null); call?

Or, is this the wrong/stupid way of achieving an asynchronous call? Can you please point me to a better example of doing this?

I would appreciate any help/comments on this issue!

Thanks,
Mattias

Hi,

I just had a similar problem. The Thread used by BeginInvoke doesn't copy the windowsIdentity from the calling thread. You have to impersonate the new thread manually:

Before calling BeginInvoke save the current identity into a variable (vb.net code):


Dim identity as WindowsIdentity
identity = System.Security.Principal.WindowsIdentity.GetCurrent()

Inside the method executed asynchronously called method use this variable and execute


identity.Impersonate

From that point on the asynchronous call uses the same priviliges than the calling thread and it should not be a problem to execute the callback.

Jan










privacy (GDPR)