Use QueueBackgroundWorkItem with user id?

I am using HostingEnvironment.QueueBackgroundWorkItem to start working in the background of an ASP.Net application based on Scott Hanselman's blog post How to run background tasks in ASP.NET .

I want to run a background job as the current user id. I tried passing WindowsPrincipal and setting Thread.CurrentPrincipal in action, but this did not result in the Action being executed as the current user.

Is this possible, or does HostingEnvironment always mean running as an application pool identifier?

Edit

Not entirely true for my original question, but I also tried passing the value through CallContext.LogicalSetData () and CallContext.LogicalGetData (). On the Get side, the value is always null.

Edit # 2

Also tried this on the queue side:

 using (HostingEnvironment.Impersonate(windowsIdentity.Token)) { HostingEnvironment.QueueBackgroundWorkItem(work); } 

When the job is actually done, the current WindowsIdentity in action is still the application pool identifier.

+8
c # impersonation
source share
2 answers

Any specific reason you should use HostingEnvironment?

or did you try to use the WindowsImpersonationContext?

 System.Security.Principal.WindowsImpersonationContext impersonationContext; impersonationContext = ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate(); //Insert your code that runs under the security context of the authenticating user here. impersonationContext.Undo(); 

you can learn more how to do it here

0
source share

The identifier of the current user is attached to the thread processing the request, and is valid only for the lifetime of this request. Even if you passed a link to HttpContext.Current.User.Identity to your working function, you will find that it can no longer be valid when you try to use it. As far as I can tell, you need to work a bit with the Windows API to clone an identity token in order to create a new WindowsIdentity , which can then be used in a background task. So something like this:

 IntPtr copy = IntPtr.Zero, token = ((WindowsIdentity)HttpContext.Current.User.Identity).Token; if (DuplicateToken(token, ref copy)) // the WinAPI function has more parameters, this is a hypothetical wrapper { return new WindowsIdentity(copy); } // handle failure 

Pass this WindowsIdentity into a background job and issue it when you need to. Do not forget to dispose of it.

0
source share

All Articles