Procedimiento para crear una directiva de autorización personalizadaHow to: Create a Custom Authorization Policy

La infraestructura del modelo de identidad de Windows Communication Foundation (WCF) admite un modelo de autorización basado en notificaciones.The Identity Model infrastructure in Windows Communication Foundation (WCF) supports a claim-based authorization model. Las notificaciones se extraen de los tokens, procesados opcionalmente por la directiva de autorización personalizada. Después se colocan en un AuthorizationContext que se puede examinar a continuación para tomar las decisiones de autorización.Claims are extracted from tokens, optionally processed by custom authorization policy, and then placed into an AuthorizationContext that can then be examined to make authorization decisions. Se puede utilizar una directiva personalizada para transformar las notificaciones de tokens entrantes en notificaciones esperadas por la aplicación.A custom policy can be used to transform claims from incoming tokens into claims expected by the application. De esta manera, el nivel de aplicación se puede aislar de los detalles de las distintas notificaciones servidas por los diferentes tipos de token que admite WCF.In this way, the application layer can be insulated from the details on the differing claims served up by the different token types that WCF supports. En este tema se muestra cómo implementar una directiva de autorización personalizada y cómo agregarla a la colección de directivas utilizada por un servicio.This topic shows how to implement a custom authorization policy and how to add that policy to the collection of policies used by a service.

Para implementar una directiva de autorización personalizadaTo implement a custom authorization policy

  1. Defina una nueva clase derivada de IAuthorizationPolicy.Define a new class that derives from IAuthorizationPolicy.

  2. Implemente la propiedad Id de solo lectura generando una cadena única en el constructor para la clase y devolviendo esa cadena cada vez que se tenga acceso a la propiedad.Implement the read-only Id property by generating a unique string in the constructor for the class and returning that string whenever the property is accessed.

  3. Implemente la propiedad Issuer de solo lectura devolviendo un ClaimSet que representa el emisor de la directiva.Implement the read-only Issuer property by returning a ClaimSet that represents the policy issuer. Éste podría ser ClaimSet, que representa la aplicación o un ClaimSet integrado (por ejemplo, el ClaimSet devuelto por la propiedad System estática.This could be a ClaimSet that represents the application or a built-in ClaimSet (for example, the ClaimSet returned by the static System property.

  4. Implemente el método Evaluate(EvaluationContext, Object) tal y como se ha descrito en el procedimiento siguiente.Implement the Evaluate(EvaluationContext, Object) method as described in the following procedure.

Para implementar el método de evaluaciónTo implement the Evaluate method

  1. Dos parámetros se pasan a este método: una instancia de la clase EvaluationContext y una referencia de objeto.Two parameters are passed to this method: an instance of the EvaluationContext class and an object reference.

  2. Si la Directiva de autorización personalizada agrega ClaimSet instancias sin tener en cuenta el contenido actual de EvaluationContext , agregue cada ClaimSet una de ellas llamando al AddClaimSet(IAuthorizationPolicy, ClaimSet) método y devolviendo true desde el Evaluate método.If the custom authorization policy adds ClaimSet instances without regard to the current content of the EvaluationContext, then add each ClaimSet by calling the AddClaimSet(IAuthorizationPolicy, ClaimSet) method and return true from the Evaluate method. Devolver true indica a la infraestructura de la autorización que la directiva de autorización ha realizado su trabajo y no necesita ser llamada de nuevo.Returning true indicates to the authorization infrastructure that the authorization policy has performed its work and does not need to be called again.

  3. Si la directiva de autorización personalizada agrega conjuntos de notificaciones solo si algunas notificaciones están presentes en EvaluationContext, después búsquelas examinando las instancias ClaimSet devueltas por la propiedad ClaimSets.If the custom authorization policy adds claim sets only if certain claims are already present in the EvaluationContext, then look for those claims by examining the ClaimSet instances returned by the ClaimSets property. Si las notificaciones están presentes, añada los nuevos conjuntos de notificaciones llamando al método AddClaimSet(IAuthorizationPolicy, ClaimSet) y, si no se van a agregar más conjuntos de notificaciones, devuelva true, indicando a la infraestructura de autorización que la directiva de autorización ha completado su trabajo.If the claims are present, then add the new claim sets by calling the AddClaimSet(IAuthorizationPolicy, ClaimSet) method and, if no more claim sets are to be added, return true, indicating to the authorization infrastructure that the authorization policy has completed its work. Si las notificaciones no están presentes, devuelva false, indicando que se debería llamar a la directiva de autorización de nuevo si otras directivas de autorización agregan más conjuntos de notificaciones a EvaluationContext.If the claims are not present, return false, indicating that the authorization policy should be called again if other authorization policies add more claim sets to the EvaluationContext.

  4. En escenarios de procesamiento más complejos, el segundo parámetro del método Evaluate(EvaluationContext, Object) se utiliza para almacenar una variable de estado que la infraestructura de autorización devolverá durante cada llamada posterior realizada al método Evaluate(EvaluationContext, Object) para una evaluación determinada.In more complex processing scenarios, the second parameter of the Evaluate(EvaluationContext, Object) method is used to store a state variable that the authorization infrastructure will pass back during each subsequent call to the Evaluate(EvaluationContext, Object) method for a particular evaluation.

Para especificar una directiva de autorización personalizada mediante la configuraciónTo specify a custom authorization policy through configuration

  1. Especifique el tipo de la directiva de autorización personalizada en el atributo policyType en el elemento add correspondiente al elemento authorizationPolicies del elemento serviceAuthorization.Specify the type of the custom authorization policy in the policyType attribute in the add element in the authorizationPolicies element in the serviceAuthorization element.

    <configuration>  
     <system.serviceModel>  
      <behaviors>  
        <serviceAuthorization serviceAuthorizationManagerType=  
                  "Samples.MyServiceAuthorizationManager" >  
          <authorizationPolicies>  
            <add policyType="Samples.MyAuthorizationPolicy" />  
          </authorizationPolicies>  
        </serviceAuthorization>  
      </behaviors>  
     </system.serviceModel>  
    </configuration>  
    

Para especificar una directiva de autorización personalizada mediante códigoTo specify a custom authorization policy through code

  1. Cree un List<T> de IAuthorizationPolicy.Create a List<T> of IAuthorizationPolicy.

  2. Cree una instancia de la directiva de autorización personalizada.Create an instance of the custom authorization policy.

  3. Agregue la instancia de la directiva de autorización a la lista.Add the authorization policy instance to the list.

  4. Repita los pasos 2 y 3 para cada directiva de autorización personalizada.Repeat steps 2 and 3 for each custom authorization policy.

  5. Asigne una versión de solo lectura de la lista a la propiedad ExternalAuthorizationPolicies.Assign a read-only version of the list to the ExternalAuthorizationPolicies property.

    // Add a custom authorization policy to the service authorization behavior.
    List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>();
    policies.Add(new MyAuthorizationPolicy());
    serviceHost.Authorization.ExternalAuthorizationPolicies = policies.AsReadOnly();
    
    ' Add custom authorization policy to service authorization behavior.
    Dim policies As List(Of IAuthorizationPolicy) = New List(Of IAuthorizationPolicy)()
    policies.Add(New MyAuthorizationPolicy())
    serviceHost.Authorization.ExternalAuthorizationPolicies = policies.AsReadOnly()
    

EjemploExample

En el siguiente ejemplo se muestra una implementación de IAuthorizationPolicy completa.The following example shows a complete IAuthorizationPolicy implementation.

public class MyAuthorizationPolicy : IAuthorizationPolicy
{
    string id;

    public MyAuthorizationPolicy()
    {
        id = Guid.NewGuid().ToString();
    }

    public bool Evaluate(EvaluationContext evaluationContext, ref object state)
    {
        bool bRet = false;
        CustomAuthState customstate = null;

        // If the state is null, then this has not been called before so
        // set up a custom state.
        if (state == null)
        {
            customstate = new CustomAuthState();
            state = customstate;
        }
        else
        {
            customstate = (CustomAuthState)state;
        }

        // If claims have not been added yet...
        if (!customstate.ClaimsAdded)
        {
            // Create an empty list of claims.
            IList<Claim> claims = new List<Claim>();

            // Iterate through each of the claim sets in the evaluation context.
            foreach (ClaimSet cs in evaluationContext.ClaimSets)
                // Look for Name claims in the current claimset.
                foreach (Claim c in cs.FindClaims(ClaimTypes.Name, Rights.PossessProperty))
                    // Get the list of operations the given username is allowed to call.
                    foreach (string s in GetAllowedOpList(c.Resource.ToString()))
                    {
                        // Add claims to the list.
                        claims.Add(new Claim("http://example.org/claims/allowedoperation", s, Rights.PossessProperty));
                        Console.WriteLine("Claim added {0}", s);
                    }

            // Add claims to the evaluation context.
            evaluationContext.AddClaimSet(this, new DefaultClaimSet(this.Issuer, claims));

            // Record that claims were added.
            customstate.ClaimsAdded = true;

            // Return true, indicating that this method does not need to be called again.
            bRet = true;
        }
        else
        {
            // Should never get here, but just in case, return true.
            bRet = true;
        }

        return bRet;
    }

    public ClaimSet Issuer
    {
        get { return ClaimSet.System; }
    }

    public string Id
    {
        get { return id; }
    }

    // This method returns a collection of action strings that indicate the
    // operations the specified username is allowed to call.
    private IEnumerable<string> GetAllowedOpList(string username)
    {
        IList<string> ret = new List<string>();

        if (username == "test1")
        {
            ret.Add("http://Microsoft.ServiceModel.Samples/ICalculator/Add");
            ret.Add("http://Microsoft.ServiceModel.Samples/ICalculator/Multiply");
            ret.Add("http://Microsoft.ServiceModel.Samples/ICalculator/Subtract");
        }
        else if (username == "test2")
        {
            ret.Add("http://Microsoft.ServiceModel.Samples/ICalculator/Add");
            ret.Add("http://Microsoft.ServiceModel.Samples/ICalculator/Subtract");
        }
        return ret;
    }

    // Internal class for keeping track of state.
    class CustomAuthState
    {
        bool bClaimsAdded;

        public CustomAuthState()
        {
            bClaimsAdded = false;
        }

        public bool ClaimsAdded
        {
            get { return bClaimsAdded; }
            set { bClaimsAdded = value; }
        }
    }
}

Public Class MyAuthorizationPolicy
    Implements IAuthorizationPolicy
    Private id_Value As String


    Public Sub New()
        id_Value = Guid.NewGuid().ToString()

    End Sub


    Public Function Evaluate(ByVal evaluationContext As EvaluationContext, ByRef state As Object) As Boolean _
        Implements IAuthorizationPolicy.Evaluate
        Dim bRet As Boolean = False
        Dim customstate As CustomAuthState = Nothing

        ' If the state is null, then this has not been called before, so set up
        ' our custom state.
        If state Is Nothing Then
            customstate = New CustomAuthState()
            state = customstate
        Else
            customstate = CType(state, CustomAuthState)
        End If
        ' If claims have not been added yet...
        If Not customstate.ClaimsAdded Then
            ' Create an empty list of Claims.
            Dim claims as IList(Of Claim) = New List(Of Claim)()

            ' Iterate through each of the claimsets in the evaluation context.
            Dim cs As ClaimSet
            For Each cs In evaluationContext.ClaimSets
                ' Look for Name claims in the current claimset...
                Dim c As Claim
                For Each c In cs.FindClaims(ClaimTypes.Name, Rights.PossessProperty)
                    ' Get the list of operations that the given username is allowed to call.
                    Dim s As String
                    For Each s In GetAllowedOpList(c.Resource.ToString())
                        ' Add claims to the list.
                        claims.Add(New Claim("http://example.org/claims/allowedoperation", s, Rights.PossessProperty))
                        Console.WriteLine("Claim added {0}", s)
                    Next s
                Next c
            Next cs ' Add claims to the evaluation context.    
            evaluationContext.AddClaimSet(Me, New DefaultClaimSet(Me.Issuer, claims))

            ' Record that claims were added.
            customstate.ClaimsAdded = True

            ' Return true, indicating that this does not need to be called again.
            bRet = True
        Else
            ' Should never get here, but just in case...
            bRet = True
        End If


        Return bRet

    End Function

    Public ReadOnly Property Issuer() As ClaimSet Implements IAuthorizationPolicy.Issuer
        Get
            Return ClaimSet.System
        End Get
    End Property

    Public ReadOnly Property Id() As String Implements IAuthorizationPolicy.Id
        Get
            Return id_Value
        End Get
    End Property
    ' This method returns a collection of action strings thet indicate the 
    ' operations the specified username is allowed to call.

    ' Operations the specified username is allowed to call.
    Private Function GetAllowedOpList(ByVal userName As String) As IEnumerable(Of String)
        Dim ret As IList(Of String) = new List(Of String)()
        If username = "test1" Then
            ret.Add("http://Microsoft.ServiceModel.Samples/ICalculator/Add")
            ret.Add("http://Microsoft.ServiceModel.Samples/ICalculator/Multiply")
            ret.Add("http://Microsoft.ServiceModel.Samples/ICalculator/Subtract")
        ElseIf username = "test2" Then
            ret.Add("http://Microsoft.ServiceModel.Samples/ICalculator/Add")
            ret.Add("http://Microsoft.ServiceModel.Samples/ICalculator/Subtract")
        End If
        Return ret
    End Function

    ' internal class for keeping track of state

    Class CustomAuthState
        Private bClaimsAdded As Boolean


        Public Sub New()
            bClaimsAdded = False

        End Sub


        Public Property ClaimsAdded() As Boolean
            Get
                Return bClaimsAdded
            End Get
            Set
                bClaimsAdded = value
            End Set
        End Property
    End Class
End Class

Vea tambiénSee also