如何:在服务上模拟客户端

如果在 Windows Communication Foundation (WCF) 服务上模拟客户端,则该服务可以代表该客户端执行操作。 对于受访问控制列表 (ACL) 检查的操作(例如,访问计算机上的目录和文件,或访问 SQL Server 数据库),ACL 检查针对的是客户端用户帐户。 本主题演示一些基本步骤,通过这些步骤,Windows 域中的客户端可以设置客户端模拟级别。 有关此操作的可运行示例,请参阅 Impersonating the Client。 有关客户端模拟的更多信息,请参阅委托和模拟

注意

当客户端和服务运行在同一计算机上,客户端运行在系统帐户(即 Local SystemNetwork Service)下时,如果安全会话是使用状态安全上下文令牌建立的,则不能模拟客户端。 WinForms 或控制台应用程序通常运行在当前登录的帐户下,因此,默认情况下可以模拟该帐户。 但是,如果客户端为 ASP.NET 页面,并且该页面在 IIS 6.0 或 IIS 7.0 中托管,则默认情况下,客户端会在 Network Service 帐户下运行。 默认情况下,系统提供的所有支持安全会话的绑定都使用无状态安全上下文令牌。 但是,如果客户端为 ASP.NET 页面,并且使用了具有有状态安全性上下文令牌的安全会话,则无法模拟该客户端。 有关在安全会话中使用有状态安全性上下文令牌的详细信息,请参阅如何:为安全会话创建安全上下文令牌

根据缓存的 Windows 令牌在服务上启用客户端模拟

  1. 创建服务。 有关此基本过程的教程,请参阅 Getting Started Tutorial

  2. 使用采用 Windows 身份验证并创建会话的绑定,例如 NetTcpBindingWSHttpBinding

  3. 在创建服务接口的实现时,将 OperationBehaviorAttribute 类应用于要求客户端模拟的方法。 将 Impersonation 属性设置为 Required

    [OperationBehavior(Impersonation=ImpersonationOption.Required)]
    public double Add(double a, double b)
    {
        return a + b;
    }
    
    <OperationBehavior(Impersonation:=ImpersonationOption.Required)> _
    Public Function Add(ByVal a As Double, ByVal b As Double) As Double _
       Implements ICalculator.Add
        Return a + b
    End Function
    

设置客户端允许的模拟级别

  1. 通过使用 ServiceModel Metadata Utility Tool (Svcutil.exe)创建服务客户端代码。 有关详细信息,请参阅使用 WCF 客户端访问服务

  2. 创建 WCF 客户端后,将 WindowsClientCredential 类的 AllowedImpersonationLevel 属性设置为 TokenImpersonationLevel 枚举值之一。

    注意

    若要使用 Delegation,则必须使用协商 Kerberos 身份验证(有时称为“多段” 或“多步” Kerberos)。 有关如何实现此身份验证的说明,请参阅安全性的最佳做法

    CalculatorClient client = new CalculatorClient("CalculatorEndpoint");
    client.ClientCredentials.Windows.AllowedImpersonationLevel =
        System.Security.Principal.TokenImpersonationLevel.Impersonation;
    
    Dim client As New CalculatorClient("CalculatorEndpoint")
    client.ClientCredentials.Windows.AllowedImpersonationLevel = _
        System.Security.Principal.TokenImpersonationLevel.Impersonation
    

另请参阅