将QueueBackgroundWorkItem与用户标识一起使用?

时间:2015-06-29 21:34:35

标签: c# asp.net impersonation

我使用HostingEnvironment.QueueBackgroundWorkItem在ASP.Net应用程序的后台运行工作,基于Scott Hanselman的博客文章How to run Background Tasks in ASP.NET

我想将后台任务作为当前用户的身份运行。我尝试在操作中传递WindowsPrincipal并设置Thread.CurrentPrincipal,但这并没有导致Action作为当前用户执行。

这是可能的,还是使用HostingEnvironment总是暗示作为应用程序池标识运行?

修改

不完全符合我的原始问题,但我也试图通过CallContext.LogicalSetData()和CallContext.LogicalGetData()传递一个值。在Get侧,值始终为null。

编辑#2

也在排队方面尝试了这个:

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

当工作完成后,Action中的当前WindowsIdentity仍然是应用程序池标识。

2 个答案:

答案 0 :(得分:0)

为什么你必须"使用" HostingEnvironment" ?

或您是否尝试过使用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();

您可以了解更多如何操作here

答案 1 :(得分:0)

当前用户的标识附加到处理请求的线程,并且仅在该请求的生命周期内有效。即使您将HttpContext.Current.User.Identity的引用传递给您的工作函数,您也会发现它在您尝试使用它时可能不再有效。据我所知,您需要使用Windows API进行一些工作来克隆身份令牌以创建新的WindowsIdentity,然后您可以在后台任务中使用它。所以像这样:

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

将此WindowsIdentity传递给您的后台任务,并在需要时模拟它。不要忘记丢弃它。

相关问题