【问题标题】:Use QueueBackgroundWorkItem with User Identity?将 QueueBackgroundWorkItem 与用户身份一起使用?
【发布时间】:2015-09-16 12:34:20
【问题描述】:

根据 Scott Hanselman 的博文 How to run Background Tasks in ASP.NET,我正在使用 HostingEnvironment.QueueBackgroundWorkItem 在 ASP.Net 应用程序的后台运行工作。

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

这可能吗,还是使用 HostingEnvironment 总是意味着以应用程序池身份运行?

编辑

不完全指向我最初的问题,但我也尝试通过 CallContext.LogicalSetData() 和 CallContext.LogicalGetData() 传递一个值。在 Get 端,该值始终为 null。

编辑#2

在排队方面也试过这个:

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

当工作真正完成时,Action 中当前的 WindowsIdentity 仍然是应用池标识。

【问题讨论】:

  • 文档说“这个重载方法不会将 ExecutionContext 或 SecurityContext 从调用者流向被调用者。因此,这些对象的成员,例如 CurrentPrincipal 属性,不会从调用者流向被调用者。” msdn.microsoft.com/en-us/library/…

标签: c# asp.net impersonation


【解决方案1】:

您“必须”使用“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

【讨论】:

  • 在问题的链接中查看它的作用说明。如果 AppDomain 尝试关闭,必须按原样安排它以(帮助)防止线程被杀死。
【解决方案2】:

当前用户的身份附加到处理请求的线程,并且仅在该请求的生命周期内有效。即使您将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 传递给您的后台任务,并在需要时模拟它。别忘了扔掉它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-10
    • 2020-03-12
    • 2018-05-15
    • 2011-11-25
    • 2017-05-10
    • 1970-01-01
    相关资源
    最近更新 更多