Async/Await with Entity Framework 6.1.1 and impersonation

不羁岁月 提交于 2019-12-22 04:32:01

问题


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?


回答1:


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>


来源:https://stackoverflow.com/questions/25294709/async-await-with-entity-framework-6-1-1-and-impersonation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!