【问题标题】:Client Impersonation from Web Service?来自 Web 服务的客户端模拟?
【发布时间】:2011-06-27 17:22:50
【问题描述】:

从 Web 服务模拟客户端的优点和缺点是什么? 它的优点之一是审计,与将身份对象从应用程序传递到 Web 服务相比,使用模拟进行审计有什么好处?

【问题讨论】:

    标签: .net wcf design-patterns architecture


    【解决方案1】:

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

    实现模拟的最简单方法是在服务的方法上进行声明。 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;
    

    【讨论】:

    • 缺点:要进行模拟,请求必须具有 WindowsIdentity。如果没有 windows 身份,就无法扩展服务的权限。这就是我能想到的缺点!我认为我在答案中所说的涵盖了大多数优势。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 2017-07-07
    • 2014-09-04
    • 2011-05-21
    相关资源
    最近更新 更多