通过


如何:为服务创建自定义授权管理器

Windows Communication Foundation(WCF)中的标识模型基础结构支持基于声明的可扩展授权模型。 声明从令牌中提取,可选地根据自定义授权策略进行处理,然后放入AuthorizationContext中。 授权管理器检查声明 AuthorizationContext 以做出授权决策。

默认情况下,授权决策由 ServiceAuthorizationManager 类做出;但是,可以通过创建自定义授权管理器来重写这些决策。 若要创建自定义授权管理器,请创建派生自 ServiceAuthorizationManager 并实现 CheckAccessCore 方法的类。 授权决策是在CheckAccessCore方法中做出的,该方法在授予访问权限时返回true,在拒绝访问时返回false

如果授权决策取决于消息正文的内容,请使用 CheckAccess 该方法。

由于性能问题,如果可能,应重新设计应用程序,以便授权决策不需要访问消息正文。

可以在代码或配置中注册服务的自定义授权管理器。

创建自定义授权管理器

  1. ServiceAuthorizationManager 类创建一个派生类。

    public class MyServiceAuthorizationManager : ServiceAuthorizationManager
    {
    
    
    Public Class MyServiceAuthorizationManager
        Inherits ServiceAuthorizationManager
    
    
  2. 重写 CheckAccessCore(OperationContext) 方法。

    使用传递给CheckAccessCore(OperationContext)方法的OperationContext来做出授权决策。

    下面的代码示例使用 FindClaims(String, String) 该方法查找自定义声明 http://www.contoso.com/claims/allowedoperation 以做出授权决策。

    protected override bool CheckAccessCore(OperationContext operationContext)
    {
      // Extract the action URI from the OperationContext. Match this against the claims
      // in the AuthorizationContext.
      string action = operationContext.RequestContext.RequestMessage.Headers.Action;
    
      // Iterate through the various claim sets in the AuthorizationContext.
      foreach(ClaimSet cs in operationContext.ServiceSecurityContext.AuthorizationContext.ClaimSets)
      {
        // Examine only those claim sets issued by System.
        if (cs.Issuer == ClaimSet.System)
        {
          // Iterate through claims of type "http://www.contoso.com/claims/allowedoperation".
            foreach (Claim c in cs.FindClaims("http://www.contoso.com/claims/allowedoperation", Rights.PossessProperty))
          {
            // If the Claim resource matches the action URI then return true to allow access.
            if (action == c.Resource.ToString())
              return true;
          }
        }
      }
    
      // If this point is reached, return false to deny access.
      return false;
    }
    
    Protected Overrides Function CheckAccessCore(ByVal operationContext As OperationContext) As Boolean
        ' Extract the action URI from the OperationContext. Match this against the claims.
        ' in the AuthorizationContext.
        Dim action As String = operationContext.RequestContext.RequestMessage.Headers.Action
    
        ' Iterate through the various claimsets in the AuthorizationContext.
        Dim cs As ClaimSet
        For Each cs In operationContext.ServiceSecurityContext.AuthorizationContext.ClaimSets
            ' Examine only those claim sets issued by System.
            If cs.Issuer Is ClaimSet.System Then
                ' Iterate through claims of type "http://www.contoso.com/claims/allowedoperation".
                Dim c As Claim
                For Each c In cs.FindClaims("http://www.contoso.com/claims/allowedoperation", _
                     Rights.PossessProperty)
                    ' If the Claim resource matches the action URI then return true to allow access.
                    If action = c.Resource.ToString() Then
                        Return True
                    End If
                Next c
            End If
        Next cs
        ' If this point is reached, return false to deny access.
        Return False
    
    End Function
    

使用代码注册自定义授权管理器

  1. 创建自定义授权管理器的实例并将其分配给属性 ServiceAuthorizationManager

    可以使用Authorization属性访问ServiceAuthorizationBehavior

    下面的代码示例注册 MyServiceAuthorizationManager 自定义授权管理器。

    // Add a custom authorization manager to the service authorization behavior.
    serviceHost.Authorization.ServiceAuthorizationManager =
               new MyServiceAuthorizationManager();
    
    ' Add a custom authorization manager to the service authorization behavior.
    serviceHost.Authorization.ServiceAuthorizationManager = _
        New MyServiceAuthorizationManager()
    
    

使用配置注册自定义授权管理器

  1. 打开服务的配置文件。

  2. <行为添加 serviceAuthorization><。>

    <在 serviceAuthorization> 中,添加属性serviceAuthorizationManagerType并将其值设置为表示自定义授权管理器的类型。

  3. 添加一个绑定,用于保护客户端和服务之间的通信。

    为此通信选择的绑定决定了要添加到 AuthorizationContext 中的声明,而自定义授权管理器使用这些声明来做出授权决策。 有关系统提供的绑定的更多详细信息,请参阅 系统提供的绑定

  4. 通过添加<服务>元素,并将behaviorConfiguration属性的值设置为<行为>元素的名称属性的值,将行为与服务终结点关联。

    有关配置服务终结点的详细信息,请参阅 如何:在配置中创建服务终结点

    下面的代码示例注册自定义授权管理器 Samples.MyServiceAuthorizationManager

    <configuration>
      <system.serviceModel>
        <services>
          <service
              name="Microsoft.ServiceModel.Samples.CalculatorService"
              behaviorConfiguration="CalculatorServiceBehavior">
            <host>
              <baseAddresses>
                <add baseAddress="http://localhost:8000/ServiceModelSamples/service"/>
              </baseAddresses>
            </host>
            <endpoint address=""
                      binding="wsHttpBinding_Calculator"
                      contract="Microsoft.ServiceModel.Samples.ICalculator" />
          </service>
        </services>
        <bindings>
          <WSHttpBinding>
           <binding name = "wsHttpBinding_Calculator">
             <security mode="Message">
               <message clientCredentialType="Windows"/>
             </security>
            </binding>
          </WSHttpBinding>
        </bindings>
        <behaviors>
          <serviceBehaviors>
            <behavior name="CalculatorServiceBehavior">
              <serviceAuthorization serviceAuthorizationManagerType="Samples.MyServiceAuthorizationManager,MyAssembly" />
             </behavior>
         </serviceBehaviors>
       </behaviors>
      </system.serviceModel>
    </configuration>
    

    警告

    请注意,指定 serviceAuthorizationManagerType 时,字符串必须包含完全限定的类型名称。 逗号,以及在其中定义类型的程序集的名称。 如果省略程序集名称,WCF 将尝试从 System.ServiceModel.dll加载类型。

示例

下面的代码示例演示了包含重写ServiceAuthorizationManager方法的CheckAccessCore类的基本实现。 示例代码检查AuthorizationContext自定义声明,并在该自定义声明的资源与操作true值匹配时返回OperationContext。 更完整的 ServiceAuthorizationManager 类实现,请参阅 授权策略

public class MyServiceAuthorizationManager : ServiceAuthorizationManager
{
  protected override bool CheckAccessCore(OperationContext operationContext)
  {
    // Extract the action URI from the OperationContext. Match this against the claims
    // in the AuthorizationContext.
    string action = operationContext.RequestContext.RequestMessage.Headers.Action;
  
    // Iterate through the various claim sets in the AuthorizationContext.
    foreach(ClaimSet cs in operationContext.ServiceSecurityContext.AuthorizationContext.ClaimSets)
    {
      // Examine only those claim sets issued by System.
      if (cs.Issuer == ClaimSet.System)
      {
        // Iterate through claims of type "http://www.contoso.com/claims/allowedoperation".
          foreach (Claim c in cs.FindClaims("http://www.contoso.com/claims/allowedoperation", Rights.PossessProperty))
        {
          // If the Claim resource matches the action URI then return true to allow access.
          if (action == c.Resource.ToString())
            return true;
        }
      }
    }
  
    // If this point is reached, return false to deny access.
    return false;
  }
}

Public Class MyServiceAuthorizationManager
    Inherits ServiceAuthorizationManager

    Protected Overrides Function CheckAccessCore(ByVal operationContext As OperationContext) As Boolean
        ' Extract the action URI from the OperationContext. Match this against the claims.
        ' in the AuthorizationContext.
        Dim action As String = operationContext.RequestContext.RequestMessage.Headers.Action

        ' Iterate through the various claimsets in the AuthorizationContext.
        Dim cs As ClaimSet
        For Each cs In operationContext.ServiceSecurityContext.AuthorizationContext.ClaimSets
            ' Examine only those claim sets issued by System.
            If cs.Issuer Is ClaimSet.System Then
                ' Iterate through claims of type "http://www.contoso.com/claims/allowedoperation".
                Dim c As Claim
                For Each c In cs.FindClaims("http://www.contoso.com/claims/allowedoperation", _
                     Rights.PossessProperty)
                    ' If the Claim resource matches the action URI then return true to allow access.
                    If action = c.Resource.ToString() Then
                        Return True
                    End If
                Next c
            End If
        Next cs
        ' If this point is reached, return false to deny access.
        Return False

    End Function
End Class

另见