次の方法で共有


方法 : カスタム承認ポリシーを作成する

Windows Communication Foundation (WCF) 内の識別モデル インフラストラクチャでは、クレーム ベースの承認モデルがサポートされます。クレームは、トークンから抽出され、状況に応じてカスタム承認ポリシーによって処理されてから、承認決定を行う際に確認できる AuthorizationContext に格納されます。カスタム ポリシーを使用して、入力トークンからのクレームを、アプリケーションが要求するクレームに変換することができます。この方法では、WCF がサポートするトークンの種類から抽出される個々のクレームの詳細から、アプリケーション レイヤーを分離できます。このトピックでは、カスタム承認ポリシーの実装方法と、サービスで使用するポリシーのコレクションにカスタム承認ポリシーを追加する方法について説明します。

カスタム承認ポリシーを実装するには

  1. IAuthorizationPolicy から派生する新しいクラスを定義します。

  2. クラスのコンストラクター内で一意の文字列を生成し、プロパティがアクセスされたときにその文字列を返すことによって、読み取り専用の Id プロパティを実装します。

  3. ポリシーの発行者を表す ClaimSet を返すことによって、読み取り専用の Issuer プロパティを実装します。これは、アプリケーションを表す ClaimSet、または組み込み ClaimSet (静的な System プロパティから返される ClaimSet など) にすることができます。

  4. 次の手順に従って、Evaluate メソッドを実装します。

Evaluate メソッドを実装するには

  1. このメソッドには、EvaluationContext クラスのインスタンスとオブジェクト参照の 2 つのパラメーターが渡されます。

  2. カスタム承認ポリシーで、EvaluationContext の現在の内容とは無関係に ClaimSet インスタンスを追加する場合は、AddClaimSet メソッドを呼び出して各 ClaimSet を追加し、Evaluate メソッドから true を返します。true を返すことは、承認インフラストラクチャに対して、承認ポリシーがその処理を完了したため、もう一度呼び出す必要がないことを知らせることになります。

  3. カスタム承認ポリシーで EvaluationContext 内に特定のクレームが既に存在するときにのみクレーム セットを追加する場合は、ClaimSets プロパティから返された ClaimSet インスタンスを調べて、該当するクレームを見つけます。クレームが見つかった場合は、AddClaimSet メソッドを呼び出して新しいクレーム セットを追加します。追加するクレーム セットがない場合は、true を返し、承認インフラストラクチャに承認ポリシーがその処理を完了したことを知らせます。クレームが存在しない場合は false を返し、他の承認ポリシーで EvaluationContext にさらにクレーム セットを追加する場合は、もう一度承認ポリシーを呼び出す必要があることを知らせます。

  4. より複雑な処理シナリオでは、Evaluate メソッドの 2 番目のパラメーターを使用して、特定の評価のために 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; } }
  }
}

参照

処理手順

方法 : クレームを比較する
方法 : サービスで使用するカスタム承認マネージャーを作成する
承認ポリシー

リファレンス

ServiceAuthorizationManager