The problem with your situation is that the background task runs after Thread.CurrentPrincipal . This is due to the ASP.NET model โ the request is processed in the user context, and after that all values โโcorresponding to the user are freed. So this is definitely happening to your personality. Try to save information about the user and his identity, then to impersonate him.
You can view the Microsoft support article for impersonating operations on ASP.NET sites, but I don't think this will be useful to you:
System.Security.Principal.WindowsImpersonationContext impersonationContext; impersonationContext = ((System.Security.Principal.WindowsIdentity)callingPrincipal.Identity).Impersonate(); //Insert your code that runs under the security context of the authenticating user here. impersonationContext.Undo();
or maybe you can use User.Token, something like this:
HostingEnvironment.QueueBackgroundWorkItem(token => { try { _logger.Debug("Executing queued background work item"); using (HostingEnvironment.Impersonate(callingPrincipal.Identity)) { using (var scope = DependencyResolver.BeginLifetimeScope()) { var service = scope.Resolve<T>(); action(service); } }
I suggest you look at the design of your architecture so that you can find a way to move the background operation to a different context in which the user ID will remain longer. Another way, for example, is to use passing the current OperationContext to the Task :
// store local operation context var operationContext = OperationContext.Current; TaskFactory.StartNew(() => { // initialize the current operation context OperationContext.Current = operationContext; action(); })
VMAtm source share