WCF Parallel Impersonation
-
01-07-2021 - |
Domanda
I have a WCF service with "ImpersonationOption.Required". The impersonation does not seem to flow through when using parallelism. For example:
Parallel.ForEach(items => results.Add(SystemUtil.WindowsUser.Name)
Will return a number with the impersonated user, and a number with the app pool user. Can impersonation be made to work with parallelism?
Best,
Marc
Update:
This is actual code on the IIS Service side.
[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public string[] WhoAmI(int numOfTests)
{
var tests = new List<int>();
for (var i = 0; i < numOfTests; i++)
tests.Add(i);
var results = new ConcurrentBag<string>();
Parallel.ForEach(tests, (test) => results.Add(WindowsIdentity.GetCurrent(false).Name));
return results.ToArray();
}
If I pass in numOfTests = 10, it spawns 10 tasks and return the WindowsIndentity Name of each task. What I get is ~70% "IIS APPPOOL.NET v4.0" and ~30% me.
How can I set it such that my identity always makes it into the Parallel.ForEach?
Thanks!
Soluzione
You need to take care of that yourself. Try something like this:
IntPtr token = WindowsIdentity.GetCurrent().Token;
Parallel.ForEach( Enumerable.Range( 1, 100 ), ( test ) =>
{
using ( WindowsIdentity.Impersonate( token ) )
{
Console.WriteLine( WindowsIdentity.GetCurrent( false ).Name );
}
} );
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow