Sdílet prostřednictvím


Postupy: Vytvoření vlastního správce autorizací pro službu

Infrastruktura modelu identit ve Službě Windows Communication Foundation (WCF) podporuje rozšiřitelný autorizační model založený na deklaracích. Deklarace identity se extrahují z tokenů a volitelně zpracují vlastními zásadami autorizace a pak se umístí do objektu AuthorizationContext. Autorizační manažer zkontroluje deklarace identity v AuthorizationContext rozhodnutích o autorizaci.

Ve výchozím nastavení se rozhodnutí o autorizaci provádí ServiceAuthorizationManager třídou. Tato rozhodnutí je však možné přepsat vytvořením vlastního správce autorizace. Pokud chcete vytvořit vlastního správce autorizace, vytvořte třídu, která je odvozena od ServiceAuthorizationManager metody a implementuje CheckAccessCore ji. Rozhodnutí o autorizaci se provádějí v CheckAccessCore metodě, která vrací true přístup udělený a false když je přístup odepřen.

Pokud rozhodnutí o autorizaci závisí na obsahu textu zprávy, použijte metodu CheckAccess .

Kvůli problémům s výkonem byste měli aplikaci přepracovat tak, aby rozhodnutí o autorizaci nevyžaduje přístup k textu zprávy.

Registraci vlastního správce autorizace pro službu je možné provést v kódu nebo konfiguraci.

Vytvoření vlastního správce autorizace

  1. Odvození třídy z ServiceAuthorizationManager třídy.

    public class MyServiceAuthorizationManager : ServiceAuthorizationManager
    {
    
    
    Public Class MyServiceAuthorizationManager
        Inherits ServiceAuthorizationManager
    
    
  2. Přepište metodu CheckAccessCore(OperationContext) .

    Použijte metodu OperationContext předanou CheckAccessCore(OperationContext) k rozhodování o autorizaci.

    Následující příklad kódu používá metodu FindClaims(String, String) k vyhledání vlastní deklarace identity http://www.contoso.com/claims/allowedoperation k provedení rozhodnutí o autorizaci.

    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
    

Registrace vlastního správce autorizace pomocí kódu

  1. Vytvořte instanci vlastního správce autorizace a přiřaďte ji k ServiceAuthorizationManager vlastnosti.

    K ServiceAuthorizationBehavior této vlastnosti je možné přistupovat pomocí Authorization vlastnosti.

    Následující příklad kódu zaregistruje vlastního MyServiceAuthorizationManager správce autorizace.

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

Registrace vlastního správce autorizace pomocí konfigurace

  1. Otevřete konfigurační soubor pro službu.

  2. Přidejte do< chování> serviceAuthorization>.<

    <Do serviceAuthorization> přidejte serviceAuthorizationManagerType atribut a nastavte jeho hodnotu na typ, který představuje vlastního správce autorizace.

  3. Přidejte vazbu, která zabezpečuje komunikaci mezi klientem a službou.

    Vazba zvolená pro tuto komunikaci určuje deklarace identity přidané do AuthorizationContext, které vlastní autorizační správce používá k rozhodování o autorizaci. Další podrobnosti o systémových vazbách naleznete v tématu Systémové vazby.

  4. Přidružte chování ke koncovému bodu služby přidáním prvku služby> a nastavením hodnoty behaviorConfiguration atributu na hodnotu atributu name pro <prvek chování>.<

    Další informace o konfiguraci koncového bodu služby najdete v tématu Postupy: Vytvoření koncového bodu služby v konfiguraci.

    Následující příklad kódu zaregistruje vlastního správce Samples.MyServiceAuthorizationManagerautorizace .

    <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>
    

    Upozorňující

    Všimněte si, že když zadáte serviceAuthorizationManagerType, řetězec musí obsahovat plně kvalifikovaný název typu. čárka a název sestavení, ve kterém je typ definován. Pokud název sestavení vynecháte, WCF se pokusí načíst typ z System.ServiceModel.dll.

Příklad

Následující příklad kódu ukazuje základní implementaci ServiceAuthorizationManager třídy, která zahrnuje přepsání CheckAccessCore metody. Ukázkový kód prozkoumá AuthorizationContext vlastní deklaraci identity a vrátí true , když prostředek pro danou vlastní deklaraci identity odpovídá hodnotě akce z objektu OperationContext. Ucelenější implementaci ServiceAuthorizationManager třídy najdete v tématu Zásady autorizace.

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

Viz také