允许匿名访问单个WCF服务方法

Ana*_*ion 2 c# wcf

我有一个带有消息安全性和用户名凭据的WCF服务.我的大多数方法都是以

[PrincipalPermission(SecurityAction.Demand, Role = ConstStrings.Roles.Admin)]
Run Code Online (Sandbox Code Playgroud)

并且这些方法应该仅由经过身份验证的用户调用.

我想添加一个匿名调用的方法,但是我收到一个错误:

未提供用户名.在ClientCredentials中指定用户名.

我喜欢类似MVC的[AllowAnonymous]属性

Cha*_*nya 7

一种选择是实现自己的ServiceAuthorizationManager并使用自己的自定义属性而不是PrincipalPermission

基本上,你将不得不继承ServiceAuthorizationManager.通过在web.config中添加以下配置,将其插入到WCF管道中(假设您的类在Org.Namespace命名空间中称为"CustomAuthorizationManager").

<behaviors>
  <serviceBehaviors>
    <behavior>
      <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
      <serviceMetadata httpGetEnabled="true" />
      <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
      <serviceDebug includeExceptionDetailInFaults="true" />
      <!--<serviceAuthorization impersonateCallerForAllOperations="true" />-->
      <serviceAuthorization serviceAuthorizationManagerType="Org.Namespace.CustomAuthorizationManager, Org.Namespace" />
    </behavior>
  </serviceBehaviors>
</behaviors>
Run Code Online (Sandbox Code Playgroud)

在自定义Authorization类中,您必须覆盖该CheckAccessCore方法,如下所示.在那里,您可以检查您创建的自定义属性(这将只是您将使用您想要的任何属性创建的普通.Net属性).

    protected override bool CheckAccessCore(OperationContext operationContext)
    {
        string action = operationContext.IncomingMessageHeaders.Action;
        DispatchOperation operation = operationContext.EndpointDispatcher.DispatchRuntime.Operations.FirstOrDefault(o => o.Action == action);
        Type hostType = operationContext.Host.Description.ServiceType;
        MethodInfo method = hostType.GetMethod(operation.Name);
        var myCustomAttributeOnMethod = method.GetCustomAttributes(true).Where(a => a.GetType() == typeof (MyCustomAttribute)).Cast<MyCustomAttribute>();
    .
    .
    .
    }        
Run Code Online (Sandbox Code Playgroud)

现在,您可以检查自定义属性并根据需要执行任何功能.例如,如果设置了自定义属性的"AllowAnonymous"标志,则可以跳过角色检查.否则,您可能会获得用户的Windows身份并检查他们是否处于特定角色.

当然,您需要使用自定义属性而不是PrincipalPermission来装饰相关方法.

总而言之,基本上你正在做的是用你自己的普通自定义.Net属性来装饰你的所有方法,它提供了一些信息.即此方法允许匿名,此方法需要此角色等.然后,您更新web.config文件以告知WCF使用您自己的服务授权管理器.您可以实现自己的服务授权管理器,您可以访问正在调用的方法,检查它的自定义属性并相应地说"Yay"或"Nay".