IIS Windows Authentication/Delegation issue with C# Parallel Tasks

When you use double-hop authentication (WebBrowser->IIS->SQL Server) code executed on the webserver inside Parallel.Invoke() or Task.Factory.StartNew() is no longer executed as authenticated user (domain\username) but is being changed to (domain\iisservername$). You can see it in Environment.UserName when debuging. So if you're executing any SQL queries as Tasks you might get permission denied errors.

The way to fix it is to pass custom TaskScheduler from CurrentSynchronizationContext

Parallel.Invoke(
  new ParallelOptions()
  {
    TaskScheduler = TaskScheduler.FromCurrentSynchronizationContext()
  },
  () => { /*do something here;*/ },
);
 
Task.Factory.StartNew(
  () => { /*do something here;*/ }, 
  CancellationToken.None, 
  TaskCreationOptions.None,
  TaskScheduler.FromCurrentSynchronizationContext()
);

This is a good article about SynchronizationContext It's All About the SynchronizationContext

Comments

  1. Task.Factory.StartNew() is no longer executed as authenticated user (domain\username) but is being changed to (domain\iisservername$). You can see it in Environment.UserName when debuging. domain.com coupons

    ReplyDelete

Post a Comment

Popular posts from this blog

Parse XML to dynamic object in C#

C# Updating GUI from different thread