【发布时间】:2011-06-27 17:22:50
【问题描述】:
从 Web 服务模拟客户端的优点和缺点是什么? 它的优点之一是审计,与将身份对象从应用程序传递到 Web 服务相比,使用模拟进行审计有什么好处?
【问题讨论】:
标签: .net wcf design-patterns architecture
从 Web 服务模拟客户端的优点和缺点是什么? 它的优点之一是审计,与将身份对象从应用程序传递到 Web 服务相比,使用模拟进行审计有什么好处?
【问题讨论】:
标签: .net wcf design-patterns architecture
模拟的目的是将服务的访问权限扩展到可能被禁止使用的资源。它通过考虑请求者的权利来做到这一点。当服务必须确定是否允许访问特定资源时,模拟使服务能够假定请求者的安全上下文。
实现模拟的最简单方法是在服务的方法上进行声明。 OperationBehavior 特性包括一个名为 Impersonation 的属性。此属性可以设置为必需或允许。
[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
public bool Update()
{
return true;
}
如果模拟属性设置为允许,则客户端凭据可以流向服务。如果模拟设置为必需,则服务必须采用客户端的凭据。
有时并非所有方法都需要模拟。例如,也许只有在访问文件时才需要模拟。为此,可以使用 WindowsImpersonationContext 类强制实现模拟。
首先,您必须检索与当前请求关联的 Windows 身份。这可通过 ServiceSecurityContext.Current 对象获得。如果 WindowsIdentity 属性不为空(记住模拟需要 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;
【讨论】: