共用方式為


HOW TO:建立自訂授權原則

Windows Communication Foundation (WCF) 中的識別模型基礎結構支援宣告架構的授權模型。 宣告會從權杖擷取出來 (可以選擇性地由自訂授權原則進行處理),接著會放置到可隨後進行檢查以做出授權決策的 AuthorizationContext。 自訂原則可用於將來自傳入權杖的宣告轉換為應用程式所需要的宣告。 如此一來,應用程式層就可以和受 WCF 支援之不同權杖類型所服務之不同宣告的詳細資料達成隔離。 本主題會說明如何實作自訂授權原則,以及如何將該原則新增至服務所使用的原則集合。

實作自訂授權原則

  1. 定義衍生自 IAuthorizationPolicy 的新類別。

  2. 透過在類別的建構函式 (Constructor) 中產生唯一字串,並在每次存取該屬性時傳回該字串,便可實作唯讀的 Id 屬性。

  3. 透過傳回表示原則簽發者的 ClaimSet,便可實作唯讀的 Issuer 屬性。 這可能是表示應用程式的 ClaimSet 或內建的 ClaimSet (例如,由靜態 System 屬性傳回的 ClaimSet)。

  4. 實作 Evaluate 方法,如下列程序所述。

實作 Evaluate 方法

  1. 有兩個參數會傳遞至這個方法:即 EvaluationContext 類別的執行個體,以及某個物件參考。

  2. 若是不論 EvaluationContext 的目前內容為何,自訂授權原則都會新增 ClaimSet 執行個體,則請呼叫 AddClaimSet 方法來新增每個 ClaimSet,並從 Evaluate 方法傳回 true。 傳回 true,就是向授權基礎結構表示該授權原則已執行其工作,因此不需要重新呼叫。

  3. 如果自訂授權原則只會在 EvaluationContext 中已出現某些宣告時新增宣告集,則請檢查 ClaimSets 屬性所傳回的 ClaimSet 執行個體來查看這些宣告。 如果這些宣告有存在,則呼叫 AddClaimSet 方法來新增新的宣告集,如果沒有要新增其他宣告集,則傳回 true,向授權基礎結構表示授權原則已完成其工作。 如果沒有存在這些宣告,則傳回 false,表示如果有其他授權原則要新增更多宣告集至 EvaluationContext,就應該重新呼叫授權原則。

  4. 在更複雜的處理案例中,Evaluate 方法的第二個參數可用來儲存狀態變數,也就是授權基礎結構後來要進行特定評估而呼叫 Evaluate 方法時所傳回的變數。

透過組態指定自訂授權原則

  1. serviceAuthorization 項目之 authorizationPolicies 項目的 add 項目的 policyType 屬性中,指定自訂授權原則的類型。

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

透過程式碼指定自訂授權原則

  1. 建立 IAuthorizationPolicyList

  2. 建立自訂授權原則的執行個體。

  3. 新增授權原則執行個體至清單中。

  4. 針對每個自訂授權原則重複步驟 2 和 3。

  5. 指派唯讀的清單版本至 ExternalAuthorizationPolicies 屬性。

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

範例

下列範例會示範完整的 IAuthorizationPolicy 實作。

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 'New
        
        
        Public Property ClaimsAdded() As Boolean 
            Get
                Return bClaimsAdded
            End Get
            Set
                bClaimsAdded = value
            End Set
        End Property 
    End Class 
End Class 
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; } }
  }
}

另請參閱

工作

HOW TO:比較宣告
HOW TO:為服務建立自訂授權管理員
授權原則

參考

ServiceAuthorizationManager