1

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?

Baga
  • 1,354
  • 13
  • 24
  • A `WindowsIdentity` object references a handle, which is a kernel object and therefore can't be serialized. Hangfire would have to explicitly duplicate the user's token at the time the job is queued. (I have no idea whether it can already do that, or if not, how hard it would be to add.) – Harry Johnston Nov 15 '16 at 21:56
  • ok Thanks @HarryJohnston! – Baga Nov 16 '16 at 10:21

1 Answers1

0

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);
Community
  • 1
  • 1
Baga
  • 1,354
  • 13
  • 24