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
  2. I am glad that I saw this post. It is informative blog for us and we need this type of blog thanks for share this blog, Keep posting such instructional blogs and I am looking forward for your future posts.
    Cyber Security Projects for Final Year

    JavaScript Training in Chennai

    Project Centers in Chennai

    JavaScript Training in Chennai

    ReplyDelete

Post a Comment

Popular posts from this blog

Parse XML to dynamic object in C#

Parse XML to object model in C# using XSD utility