4

私はWCFで作業しており、に基づいた認証マネージャーを作成してIHttpModuleおり、正常に動作します。Authentication私のクラスの of メソッドの 1 つは、 にGenericPrincipalオブジェクトを作成しますContext.User

例えば

app.Context.User = new GenericPrincipal(new GenericIdentity("Scott"), new string[] { "read" });

のメソッドの 1 つでService、ユーザーを割り当てたいのですが、PrincipalPermissionAttributeどのように機能するかはわかりませんが、常にSecurityException. 例えば:

    [WebGet(UriTemplate = "/", RequestFormat=WebMessageFormat.Xml, ResponseFormat=WebMessageFormat.Xml)]
    [PrincipalPermission(SecurityAction.Demand, Role="read")]  // it throw SecurityException
    public SampleItem GetCollection()
    {
        bool user = HttpContext.Current.User.IsInRole("read"); // return true
        bool user1 = HttpContext.Current.User.IsInRole("write"); // return false

        return SampleItem.GetSampleItem();
    }

たぶんPrincipalPremissionAttribute使わないContext.Current.User?しかし、そうでない場合はどうなりますか?

問題を取り除き、非常に単純な属性を作成してみました

[AttributeUsage(AttributeTargets.Method, AllowMultiple=true, Inherited=false)]
public class MyAuthorizationAttribute : Attribute
{
    public MyAuthorizationAttribute(params string[]  roles)
    {
        foreach (string item in roles)
        {
            if(HttpContext.Current.User.IsInRole(item) == false)
            {
                HttpContext.Current.Response.Clear();

                HttpContext.Current.Response.StatusCode = 401;

                HttpContext.Current.Response.AddHeader("WWW-Authenticate", "Basic Realm");
                HttpContext.Current.Response.StatusDescription = "Access Denied";
                HttpContext.Current.Response.Write("401 Access Denied");

                HttpContext.Current.Response.End();
            }
        }
    }
}

しかし、アプリケーションはこれを使用できません。つまり、コンストラクターにブレークポイントを設定するMyAttributeと、コンパイラーはビークポイントで停止せず、認識しません。

    [WebGet(UriTemplate = "/", RequestFormat=WebMessageFormat.Xml, ResponseFormat=WebMessageFormat.Xml)]
    [MyAuthorization("read")]
    public SampleItem GetCollection()
    {
        bool user = HttpContext.Current.User.IsInRole("read"); // return true
        bool user1 = HttpContext.Current.User.IsInRole("write"); // return false

        return SampleItem.GetSampleItem();
    }
4

1 に答える 1

3

WCF では、非常に特殊なメカニズムを介してカスタム プリンシパルを関連付ける必要がありますが、これは正常に機能します。また、属性は一般にコード実行を引き起こさ 、リフレクションを介して明示的に実行された場合にのみ呼び出されることに注意してください (PostSharp を使用している場合を除く)。属性を追加するだけで自動的に処理を実行させることはできません。MVCなどはその印象を与えますが、MVCには属性をチェックして手動で実行するコードがあります。

于 2011-02-27T21:14:08.623 に答える