WCF服务中的TPL任务无法使用正确的IIS安全凭据(SQL连接) [英] TPL Task in WCF service fails to use correct IIS security Credentials (SQL Connection)

查看:107
本文介绍了WCF服务中的TPL任务无法使用正确的IIS安全凭据(SQL连接)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a WCF service method that calls a SQL stored proc. I'm developing using IIS 5 (can't do much about that, II6/7 not available)

为了获得一些收益,我通过将调用放入c#TPL Task中,对该存储的proc进行了许多异步调用.

To get some gains, I'm doing a number of async calls to this stored proc by putting the call into a c# TPL Task.

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

When run as a Task, I'm getting an SQL Exception... "Login failed. The login is from an untrusted domain and cannot be used with Windows authentication"

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

However, If I run the exact same process without using a Task, I have no problems with SQL connection

在我看来,IIS虚拟文件夹(WCF)的凭据没有被委派给任务?有什么想法可以具体说明TPL Task线程的凭据,即使用与父代等相同的凭据吗?

It would appear to me that the credentials for the IIS Virtual folder (WCF) are not being delegated to the Task? Any ideas how I can specificy credentials for the TPL Task thread, ie to use the same as the parent etc ?

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

I am using Windows Authentication (sspi), and impersonation to be able to connect to the seperate SQL box.

感谢您的帮助.

推荐答案

您有两种选择.

1)使用以下方法让您的整个应用程序始终使用身份流:

1) Opt your entire application into always flowing the identity using:

<runtime>
    <alwaysFlowImpersonationPolicy enabled="true"/>
</runtime>

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

This has a side effect of overhead and the danger of accidentally executing some unintended code with the priviledges of the currently calling user rather than the application identity. I would personally avoid this and go with #2 where you explicitly opt-in.

2)设置您的 WindowsIdentity TPL任务,并使用 Impersonate + WindowsImpersonationContext :

2) Capture the WindowsIdentity before setting up your TPL tasks and explicitly impersonate where you need to make the calls using 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
    });  
}

这篇关于WCF服务中的TPL任务无法使用正确的IIS安全凭据(SQL连接)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆