WCF服务中的TPL任务无法使用正确的IIS安全凭据(SQL连接)

Ron*_*ton 4 sql wcf iis-5 task-parallel-library

我有一个调用SQL存储过程的WCF服务方法.我正在使用IIS 5开发(不能做太多,II6/7不可用)

为了获得一些收益,我通过将调用放入ac#TPL任务来对此存储过程进行多次异步调用.

当作为任务运行时,我收到SQL异常..."登录失败.登录来自不受信任的域,不能与Windows身份验证一起使用"

但是,如果我在不使用任务的情况下运行完全相同的进程,则SQL连接没有问题

在我看来,IIS虚拟文件夹(WCF)的凭据未被委托给任务?任何想法如何我可以具体化TPL任务线程的凭证,即使用相同的父母等?

我正在使用Windows身份验证(sspi)和模拟,以便能够连接到单独的SQL框.

你的帮助表示赞赏

Dre*_*rsh 5

你有两个选择.

1)选择使用以下内容来整个应用程序:

<runtime>
    <alwaysFlowImpersonationPolicy enabled="true"/>
</runtime>
Run Code Online (Sandbox Code Playgroud)

这具有开销的副作用以及意外执行某些非预期代码与使用当前调用用户的特权而不是应用程序标识的危险.我个人会避免这种情况,并在#2中明确选择加入.

2)WindowsIdentity在设置TPL任务之前捕获,并使用Impersonate+ 显式模拟您需要拨打电话的位置WindowsImpersonationContext:

public void SomeWCFOperation()
{
    WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();

    Task.Factory.StartNew(() =>
    {
         // some unpriviledged code here


         using(WindowsImpersonationContext impersonationContext = currentIdentity.Impersonate())
         {
            // this code will execute with the priviledges of the caller
         }

         // some more unpriviledged code here
    });  
}
Run Code Online (Sandbox Code Playgroud)