Search code examples
c#.netasp.net-web-apiwindows-authenticationhangfire

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


In our application we have Web API queuing jobs to be run in background. We use HangFire for the background processing of jobs. The Web API uses Windows Authentication. Hangfire server is configured to run as a windows service.

I'm trying to execute the background Jobs as the same user who queued them.

I tried passing WindowsIdentity.GetCurrent() (serialized and passed by hangfire) the exception thrown is "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);
}

Came across a approach calling WIN32 API method Logon user. But since that takes password as input not sure how to use it.

Any way to execute the background Jobs as the same user who queued them?


Solution

  • Possible Solutions:

    1. Using Win32 API calls. Drawback is that, this method requires users password. More details in below SO question.

    Windows Impersonation and duplicating tokens

    1. Using Kerberos Extension '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);