Поделиться через


Практическое руководство. Создание пользовательской политики авторизации

Инфраструктура модели удостоверений в Windows Communication Foundation (WCF) поддерживает модель авторизации на основе утверждений. Утверждения извлекаются из маркеров, дополнительно обрабатываемых пользовательской политикой авторизации, и затем помещаются в контекст AuthorizationContext, который позже может проверяться для принятия решений по авторизации. Пользовательская политика может использоваться для преобразования утверждений из входящих маркеров в утверждения, ожидаемые приложением. Таким образом, уровень приложений может быть изолирован от сведений о различных утверждениях, обслуживаемых различными типами маркеров, поддерживаемыми WCF. В данном разделе показываются реализация пользовательской политики авторизации и добавление этой политики в коллекцию политик, используемых службой.

Реализация пользовательской политики авторизации

  1. Определите новый класс, наследуемый от IAuthorizationPolicy.

  2. Реализуйте предназначенное только для чтения свойство Id посредством создания уникальной строки в конструкторе для данного класса и возврата этой строки при каждом доступе к данному свойству.

  3. Реализуйте предназначенное только для чтения свойство Issuer посредством возврата набора ClaimSet, представляющего поставщика политики. Это может быть набор ClaimSet, который представляет приложение, или встроенный набор ClaimSet (например, набор ClaimSet, возвращаемый статическим свойством System).

  4. Реализуйте метод Evaluate(EvaluationContext, Object) согласно описанию в следующей процедуре.

Реализация метода Evaluate

  1. В этот метод передаются два параметра: экземпляр класса EvaluationContext и ссылка на объект.

  2. Если настраиваемая политика авторизации добавляет ClaimSet экземпляры без учета текущего содержимого объекта EvaluationContext, добавьте каждый ClaimSet из них путем вызова AddClaimSet(IAuthorizationPolicy, ClaimSet) метода и возврата true из Evaluate метода. Возврат значения true указывает инфраструктуре авторизации, что политика авторизации выполнила свою работу и снова ее вызывать не требуется.

  3. Если пользовательская политика авторизации добавляет наборы утверждений только в случае наличия определенных утверждений в классе EvaluationContext, выполните поиск этих утверждений, проверив экземпляры ClaimSet, возвращенные свойством ClaimSets. Если утверждения присутствуют, добавьте новые наборы утверждений, вызвав метод AddClaimSet(IAuthorizationPolicy, ClaimSet), и в случае отсутствия необходимости добавления дополнительных наборов утверждений верните значение true, указывающее инфраструктуре авторизации, что политика авторизации завершила свою работу. Если утверждения отсутствуют, верните значение false, указывающее, что в случае добавления дополнительных наборов утверждений в класс EvaluationContext другими политиками авторизации политика авторизации должна быть вызвана снова.

  4. В более сложных сценариях обработки второй параметр метода Evaluate(EvaluationContext, Object) используется для хранения переменной состояния, которую инфраструктура авторизации будет передавать назад в течение каждого последующего вызова метода Evaluate(EvaluationContext, Object) для конкретной оценки.

Задание пользовательской политики авторизации с помощью конфигурации

  1. Задайте тип пользовательской политики авторизации с помощью атрибута policyType в элементе add элемента authorizationPolicies в элементе serviceAuthorization.

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

Задание пользовательской политики авторизации с помощью кода

  1. Создайте список List<T> политики IAuthorizationPolicy.

  2. Создайте экземпляр пользовательской политики авторизации.

  3. Добавьте экземпляр политики авторизации в список.

  4. Повторите шаги 2 и 3 для каждой пользовательской политики авторизации.

  5. Присвойте предназначенную только для чтения версию списка свойству 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()
    

Пример

В следующем примере показана полная реализация IAuthorizationPolicy.

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

См. также