Dela via


Anvisningar: Skapa en anpassad auktoriseringshanterare för en tjänst

Identity Model-infrastrukturen i Windows Communication Foundation (WCF) stöder en utökningsbar anspråksbaserad auktoriseringsmodell. Anspråk extraheras från token och bearbetas eventuellt av anpassade auktoriseringsprinciper och placeras sedan i en AuthorizationContext. En auktoriseringshanterare undersöker anspråken AuthorizationContext i för att fatta auktoriseringsbeslut.

Som standard fattas auktoriseringsbeslut av ServiceAuthorizationManager klassen, men dessa beslut kan åsidosättas genom att skapa en anpassad auktoriseringshanterare. Skapa en anpassad auktoriseringshanterare genom att skapa en klass som härleds från ServiceAuthorizationManager och implementera CheckAccessCore metoden. Auktoriseringsbeslut fattas i CheckAccessCore metoden, som returnerar true när åtkomst beviljas och false när åtkomst nekas.

Om auktoriseringsbeslutet beror på innehållet i meddelandetexten använder du CheckAccess metoden .

På grund av prestandaproblem bör du om möjligt göra om programmet så att auktoriseringsbeslutet inte kräver åtkomst till meddelandetexten.

Registrering av den anpassade auktoriseringshanteraren för en tjänst kan göras i kod eller konfiguration.

Skapa en anpassad auktoriseringshanterare

  1. Härled en klass från ServiceAuthorizationManager klassen.

    public class MyServiceAuthorizationManager : ServiceAuthorizationManager
    {
    
    
    Public Class MyServiceAuthorizationManager
        Inherits ServiceAuthorizationManager
    
    
  2. Åsidosätt CheckAccessCore(OperationContext) metoden.

    Använd som OperationContext skickas till CheckAccessCore(OperationContext) metoden för att fatta auktoriseringsbeslut.

    I följande kodexempel används FindClaims(String, String) metoden för att hitta det anpassade anspråket http://www.contoso.com/claims/allowedoperation för att fatta ett auktoriseringsbeslut.

    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
    

Registrera en anpassad auktoriseringshanterare med hjälp av kod

  1. Skapa en instans av den anpassade auktoriseringshanteraren och tilldela den ServiceAuthorizationManager till egenskapen.

    Kan ServiceAuthorizationBehavior nås med hjälp av Authorization egenskapen .

    I följande kodexempel registreras den MyServiceAuthorizationManager anpassade auktoriseringshanteraren.

    // 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()
    
    

Registrera en anpassad auktoriseringshanterare med hjälp av konfiguration

  1. Öppna konfigurationsfilen för tjänsten.

  2. Lägg till en serviceAuthorization> i beteendena><.<

    <I serviceAuthorization> lägger du till ett serviceAuthorizationManagerType attribut och anger dess värde till den typ som representerar den anpassade auktoriseringshanteraren.

  3. Lägg till en bindning som skyddar kommunikationen mellan klienten och tjänsten.

    Bindningen som väljs för den här kommunikationen avgör de anspråk som läggs till i AuthorizationContext, som den anpassade auktoriseringshanteraren använder för att fatta auktoriseringsbeslut. Mer information om bindningar som tillhandahålls av systemet finns i Bindningar som tillhandahålls av systemet.

  4. Associera beteendet till en tjänstslutpunkt genom att lägga till ett tjänstelement> och ange värdet behaviorConfiguration för attributet till värdet för namnattributet för <beteendeelementet>.<

    Mer information om hur du konfigurerar en tjänstslutpunkt finns i Så här skapar du en tjänstslutpunkt i Konfiguration.

    I följande kodexempel registreras den anpassade auktoriseringshanteraren 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>
    

    Varning

    Observera att när du anger serviceAuthorizationManagerType måste strängen innehålla det fullständigt kvalificerade typnamnet. ett kommatecken och namnet på sammansättningen där typen definieras. Om du utelämnar sammansättningsnamnet försöker WCF läsa in typen från System.ServiceModel.dll.

Exempel

I följande kodexempel visas en grundläggande implementering av en ServiceAuthorizationManager klass som omfattar åsidosättande av CheckAccessCore metoden. Exempelkoden undersöker AuthorizationContext för ett anpassat anspråk och returnerar true när resursen för det anpassade anspråket matchar åtgärdsvärdet från OperationContext. En mer fullständig implementering av en ServiceAuthorizationManager klass finns i Auktoriseringsprincip.

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

Se även