Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use QueueBackgroundWorkItem with User Identity?

I am using HostingEnvironment.QueueBackgroundWorkItem to run work in the background of an ASP.Net application, based on Scott Hanselman's blog post How to run Background Tasks in ASP.NET.

I'd like to run the background task as the current user's identity. I have tried passing a WindowsPrincipal and setting Thread.CurrentPrincipal in the action, but this didn't result in the Action executing as the current user.

Is this possible, or does using HostingEnvironment always imply running as the App pool identity?

Edit

Not exactly on point to my original question, but I also tried to pass a value via CallContext.LogicalSetData() and CallContext.LogicalGetData(). On the Get side, the value is always null.

Edit #2

Also tried this on the queuing side:

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

When the work is actually done, the current WindowsIdentity in the Action is still the app pool identity.

like image 935
Phil Sandler Avatar asked Jun 29 '15 21:06

Phil Sandler


1 Answers

any specific reason why you "must" use "HostingEnvironment" ?

or Have you tried 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 find out more how to do it here

like image 119
ronnie Avatar answered Oct 14 '22 06:10

ronnie