运行 与排队的用户在不同进程中的后台作业

Run a background job in a different process as the user who queued it

在我们的应用程序中,Web API 排队作业在后台 运行。我们使用 HangFire 进行作业的后台处理。 Web API 使用 Windows 身份验证。 Hangfire 服务器配置为 运行 作为 windows 服务。

我正在尝试以排队的用户身份执行后台作业。

我尝试传递 WindowsIdentity.GetCurrent() (由 hangfire 序列化并传递)抛出的异常是 "Invalid token for impersonation - it cannot be duplicated"

[HttpGet, Route("enq")]
public IHttpActionResult EnQueue(string country)
{     
    var curUser = System.Security.Principal.WindowsIdentity.GetCurrent();           
    var id = Hangfire.BackgroundJob.Enqueue(() => Services.Common.TestClass.Test(curUser , country));
    return Ok(id);
}

遇到一个调用 WIN32 API method Logon user 的方法。但是因为它需要密码作为输入不知道如何使用它。

有什么方法可以让后台作业与排队的用户相同?

可能的解决方案:

  1. 使用 Win32 API 调用。缺点是,此方法需要用户密码。下面的 SO 问题中有更多详细信息。

Windows Impersonation and duplicating tokens

  1. 使用 Kerberos 扩展 'Service For User Logon'

https://blogs.msdn.microsoft.com/winsdk/2015/08/28/logon-as-a-user-without-a-password/

var upn = System.DirectoryServices.AccountManagement.UserPrincipal.Current.UserPrincipalName;
WindowsIdentity s4u = new WindowsIdentity(upn);