.net 从Web服务模拟客户端?

.net 从Web服务模拟客户端?,.net,wcf,design-patterns,architecture,.net,Wcf,Design Patterns,Architecture,从web服务模拟客户端的优点和缺点是什么? 它的优点之一是审计,如何使用模拟来审计比将身份对象从应用程序传递到web服务更好?模拟的目的是将服务的访问扩展到可能不受限制的资源。它通过考虑请求者的权利来实现这一点。当必须确定是否允许访问特定资源时,模拟使服务能够假定请求者的安全上下文 实现模拟的最简单方法是在服务的方法上声明。OperationBehavior属性包含一个名为Impersonation的属性。此属性可以设置为必需或允许 [OperationBehavior(Impersonati

从web服务模拟客户端的优点和缺点是什么?
它的优点之一是审计,如何使用模拟来审计比将身份对象从应用程序传递到web服务更好?

模拟的目的是将服务的访问扩展到可能不受限制的资源。它通过考虑请求者的权利来实现这一点。当必须确定是否允许访问特定资源时,模拟使服务能够假定请求者的安全上下文

实现模拟的最简单方法是在服务的方法上声明。OperationBehavior属性包含一个名为Impersonation的属性。此属性可以设置为必需或允许

 [OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
public bool Update()
{
return true;
}
如果模拟属性设置为Allowed,则客户端凭据可以流向服务。如果模拟设置为Required,则服务必须采用客户端的凭据

有时并非所有方法都需要模拟。例如,可能只有在访问文件时才需要模拟。为此,可以使用WindowsImpersonationContext类强制实现模拟

要开始,必须检索与当前请求关联的Windows标识。这可以通过ServiceSecurityContext.Current对象获得。如果WindowsIdentity属性不为null(请记住模拟需要Windows标识),则可以对该标识调用Impersonate方法。以下代码演示了此技术:

 WindowsIdentity callerIdentity =
    ServiceSecurityContext.Current.WindowsIdentity;
    if (callerIdentity == null)
    throw new InvalidOperationException(
    "The caller cannot be mapped to a WindowsIdentity");
    using (WindowsImpersonationContext context = callerIdentity.Impersonate())
    {
        // Access a file as the caller.
    }
到目前为止,演示的两种模拟技术都是在逐个方法的基础上运行的。还可以为服务中的所有方法启用模拟。您可以通过将ServiceAuthorization行为上的ImpersonateCallerForAllOperations属性设置为true来完成此操作。您可以按照以下代码示例所示执行此操作:

ServiceHost serviceHost = new ServiceHost(typeof(TestService));
ServiceAuthorizationBehavior behavior =
serviceHost.Description.Behaviors.Find<ServiceAuthorizationBehavior>();
behavior.ImpersonateCallerForAllOperations = true;
ServiceHost ServiceHost=newservicehost(typeof(TestService));
ServiceAuthorizationBehavior行为=
serviceHost.Description.Behaviors.Find();
behavior.ImpersonateCallerForAllOperations=true;

缺点:要进行模拟,请求必须具有WindowsIdentity。如果没有windows标识,则无法扩展服务的权限。这就是我能想到的所有不利因素!我认为我在回答中所说的涵盖了大多数优势。