Use QueueBackgroundWorkItem with User Identity? Use QueueBackgroundWorkItem with User Identity? asp.net asp.net

Use QueueBackgroundWorkItem with User Identity?


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


The current user's identity is attached to the thread handling the request, and is only valid for the lifetime of that request. Even if you passed a reference to HttpContext.Current.User.Identity to your worker function, you would find that it may no longer be valid when you try to use it. As far as I can tell, you need to do a bit of work with the Windows API to clone the identity token to make a new WindowsIdentity, which you can then use in your 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 to your background task, and impersonate it when you need to. Don't forget to dispose of it.