How do I set the new thread principal?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I start a new thread to run a long database query and show the progress bar

Thread DbThread = new Thread(new ThreadStart(dr.GetDataFromDb));
DbThread.Start()
Response.Redirect ("WaitPage.aspx")

Problem is that the new thread ignores the identity of asp_netwp.exe worker process.
There is <identity impersonate="true" /> in the web.config and I use integrated SQL Security, that is the identity of the anonymous account in IIS metabase. However, the new thread does not know anything about this and SQL connection fails

I can set processModel account, but maybe there is a better way

The Thread class has a static CurrentPrincipal member. I tried to use pass it inside the thread class, but it did not work..

Thanks

-Sta
 
You must declare the RevertToSelf function and the token variable as the class members:

[DllImport("advapi32")]
public static extern bool RevertToSelf();

protected IntPtr token;

You must save the token for the current thread and call the RevertToSelf before the new thread creation:

token = WindowsIdentity.GetCurrent().Token;
// This thread is currently impersonating so any thread we create won't have

// permission to impersonate. So we need to drop the current

// impersonation token so our new thread can impersonate.

RevertToSelf();

In the delegate function you must impersonate the identity:

// Impersonate using the Token property

WindowsIdentity wi = new WindowsIdentity(token);

WindowsImpersonationContext ctx = wi.Impersonate();

HtH,
Andrea
 
Actually, it works even withoug RevertToSelf. Here is the snippet

Main class
======
DbReader dr = new DbReader (WindowsIdentity.GetCurrent().Token)
//RevertToSelf()
Thread DbThread = new Thread(new ThreadStart(dr.GetDataFromDb))
DbThread.Start()
Response.Redirect ("Wait.aspx")
======

Delegate
=====
class DbReade

protected IntPtr token

public DbReader (IntPtr token

this.token = token


public void GetDataFromDb(
{
WindowsIdentity wi = new WindowsIdentity (token)
WindowsImpersonationContext ctx = wi.Impersonate()

// Get data..



=========

Do I need RevertToSelf()

Thanks a lot for your post, it really helpe

-Stan
 
If you need to create only one thread you don't need to use the
RevertToSelf, but if you must create other threads, if you don't call the
RevertToSelf, you 'll run into your original problem again.

HtH,
Andrea
 
Back
Top