8

I have a WCF service hosted in IIS that is retrieving data from multiple sources (all SQL Server). With each data source, I have to impersonate a different Active Directory user to connect to the database. I am using Entity Framework v6.1.1 for two of the data sources. Integrated Security is set to True in the connection strings, too.

I use the example below to set the impersonated user, where the impersonated user is a System.Security.Principal.WindowsImpersonationContext that I set from configuration:

internal async Task<List<string>> GetItemsByLookupItemsAsync(List<string> lookupItems) 
{
    var result = new List<string>();

    using (var db = new EntityFrameworkDb()) 
    {

        var query = from item in db.Table
                    where lookupItems.Contains(item.LookupColumn)
                    select item.StringColumn;

        var queryResult = new List<string>();
        using (GetImpersonatedUser())
        {
            queryResult.AddRange(await query.ToListAsync());
        }

        result.AddRange(queryResult.OrderBy(e => e));
    }

    return result;
}

The problem is that the previous code throws a SqlException saying that the account running the web service can not log on to the database. It appears that when I hit the await I lose the impersonation context.

What are some suggestions to solve this problem?

Yuval Itzchakov
  • 136,303
  • 28
  • 230
  • 296
Alan P
  • 83
  • 7
  • 1
    My usual recommendation is to not use async for database calls because it almost never does anything good. – usr Aug 13 '14 at 19:41
  • 3
    @usr Can you elaborate on that a bit more? – Yuval Itzchakov Aug 13 '14 at 19:47
  • @YuvalItzchakov I have: http://stackoverflow.com/a/25087273/122718 If you doubt this statement, try to clearly express why calling the database using async IO is helpful. It is hard to come up with reasons. – usr Aug 13 '14 at 19:48
  • 2
    @usr How about the latest comment by stephan? About the type of database being able to scale better than before. If it isn't too expensive, why not take advantage? – Yuval Itzchakov Aug 13 '14 at 20:13
  • 1
    Please read this: http://blog.codeishard.net/2012/09/17/await-async-mvc-and-impersonation/ – Matt Aug 13 '14 at 21:12

1 Answers1

7

Set the legacyImpersonationPolicy to false and alwaysFlowImpersonationPolicy to true inside your web.config and restart IIS

<configuration>
   <runtime>
     <legacyImpersonationPolicy enabled="false"/>
    <alwaysFlowImpersonationPolicy enabled="true"/>   
  </runtime>
</configuration>
Yuval Itzchakov
  • 136,303
  • 28
  • 230
  • 296
  • 1
    This worked, both in IIS in web.config and in my client app.config. Thanks for your help. – Alan P Aug 15 '14 at 12:35