Dela via


Anvisningar: Skapa en anpassad auktoriseringsprincip

Identity Model-infrastrukturen i Windows Communication Foundation (WCF) stöder en anspråksbaserad auktoriseringsmodell. Anspråk extraheras från token, eventuellt bearbetas av en anpassad auktoriseringsprincip och placeras sedan i en AuthorizationContext som sedan kan granskas för att fatta auktoriseringsbeslut. En anpassad princip kan användas för att omvandla anspråk från inkommande token till anspråk som förväntas av programmet. På så sätt kan programlagret isoleras från informationen om de olika anspråk som hanteras av de olika tokentyperna som WCF stöder. Det här avsnittet visar hur du implementerar en anpassad auktoriseringsprincip och hur du lägger till den principen i samlingen med principer som används av en tjänst.

Implementera en anpassad auktoriseringsprincip

  1. Definiera en ny klass som härleds från IAuthorizationPolicy.

  2. Implementera den skrivskyddade Id egenskapen genom att generera en unik sträng i konstruktorn för klassen och returnera strängen när egenskapen används.

  3. Implementera den skrivskyddade Issuer egenskapen genom att returnera en ClaimSet som representerar princip utfärdaren. Detta kan vara en ClaimSet som representerar programmet eller en inbyggd ClaimSet (till exempel den ClaimSet som returneras av den statiska System egenskapen.

  4. Evaluate(EvaluationContext, Object) Implementera metoden enligt beskrivningen i följande procedur.

Så här implementerar du metoden Evaluate

  1. Två parametrar skickas till den här metoden: en instans av EvaluationContext klassen och en objektreferens.

  2. Om den anpassade auktoriseringsprincipen lägger till ClaimSet instanser utan hänsyn till det aktuella innehållet i EvaluationContextlägger du till var och en ClaimSet genom att anropa AddClaimSet(IAuthorizationPolicy, ClaimSet) metoden och returnera true från Evaluate metoden. Returnerar true anger för auktoriseringsinfrastrukturen att auktoriseringsprincipen har utfört sitt arbete och inte behöver anropas igen.

  3. Om den anpassade auktoriseringsprincipen lägger till anspråksuppsättningar endast om vissa anspråk redan finns i EvaluationContextletar du efter dessa anspråk genom att undersöka de ClaimSet instanser som returneras av ClaimSets egenskapen. Om anspråken finns lägger du till de nya anspråksuppsättningarna genom att anropa AddClaimSet(IAuthorizationPolicy, ClaimSet) metoden och om inga fler anspråksuppsättningar ska läggas till returnerar du true, som anger för auktoriseringsinfrastrukturen att auktoriseringsprincipen har slutfört sitt arbete. Om anspråken inte finns returnerar du false, som anger att auktoriseringsprincipen ska anropas igen om andra auktoriseringsprinciper lägger till fler anspråksuppsättningar i EvaluationContext.

  4. I mer komplexa bearbetningsscenarier används den andra parametern Evaluate(EvaluationContext, Object) för metoden för att lagra en tillståndsvariabel som auktoriseringsinfrastrukturen skickar tillbaka under varje efterföljande anrop till Evaluate(EvaluationContext, Object) metoden för en viss utvärdering.

Så här anger du en anpassad auktoriseringsprincip via konfiguration

  1. Ange typen av anpassad auktoriseringsprincip i policyType attributet i elementet add i elementet authorizationPolicies i elementet serviceAuthorization .

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

Så här anger du en anpassad auktoriseringsprincip via kod

  1. Skapa en List<T> av IAuthorizationPolicy.

  2. Skapa en instans av den anpassade auktoriseringsprincipen.

  3. Lägg till instansen för auktoriseringsprincip i listan.

  4. Upprepa steg 2 och 3 för varje anpassad auktoriseringsprincip.

  5. Tilldela en skrivskyddad version av listan till egenskapen ExternalAuthorizationPolicies .

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

Exempel

I följande exempel visas en fullständig IAuthorizationPolicy implementering.

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

Se även