25

単純なクエリ文字列パラメーターを介して制限したいいくつかの単純なルートがあります。キーが正しくないか提供されていない場合は、NotAuthorizedException.

WebApi または同等のものを使用することを提案しないでください。このシナリオではまだできません。

したがって、実装する必要があるかどうか、実装する必要があるかどうか、または他の何かをIAuthorizationFilter実装する必要があるかどうかはわかりません。IActionFilter

私のコードロジック?

  • キーのクエリ文字列を確認してください。
  • そのキー/値を持つユーザーの RavenDb (リポジトリ) を確認してください。

これらのチェックのいずれかに失敗した場合は、NotAuthorizedException.

次に、このフィルターでアクション メソッドを装飾すると想定しています。また、リポジトリをこのアクションメソッドに渡す必要があると思いますか?

何か提案はありますか?

4

1 に答える 1

42

したがって、IAuthorizationFilter を実装する必要があるのか​​、IActionFilter を実装する必要があるのか​​ 、それとも何か他のものを実装する必要があるのか​​ わかりません。

以下を実装する必要がありますIAuthorizationFilter

public class MyAuthorizeAttribute: FilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        var key = filterContext.HttpContext.Request.QueryString["param_name"];
        if (!IsValid(key))
        {
            // Unauthorized!
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }

    private bool IsValid(string key)
    {
        // You know what to do here => go hit your RavenDb
        // and perform the necessary checks
        throw new NotImplementedException();
    }
}

また、カスタム アクション フィルターに依存性注入を使用する場合はfollowing article、カスタム フィルター プロバイダーを実装できる を参照してください ( IFilterProvider)。コントローラー アクションで使用できるマーク付き属性を設定し、このカスタム フィルター プロバイダーで、アクションがこのマーカー属性で装飾されているかどうかを確認し、カスタム承認フィルターを適用することができます。

例えば:

public class MyAuthorizeAttribute: Attribute
{

}

承認フィルターは のみを実装しIAuthorizationFilter、 にはなりませんFilterAttribute:

public class MyAuthorizationFilter: IAuthorizationFilter
{
    private readonly ISomeRepository repository;
    public class MyAuthorizationFilter(ISomeRepository repository)
    {
        this.repository = repository;
    }

    public void OnAuthorization(AuthorizationContext filterContext)
    {
        var key = filterContext.HttpContext.Request.QueryString["param_name"];
        if (!IsValid(key))
        {
            // Unauthorized!
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }

    private bool IsValid(string key)
    {
        // You know what to do here => go hit your RavenDb
        // and perform the necessary checks
        throw new NotImplementedException();
    }
}

そして、カスタム フィルター プロバイダーが作成されます。

public class MyFilterProvider : IFilterProvider
{
    public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        if (actionDescriptor.GetCustomAttributes(typeof(MyAuthorizeAttribute), true).Any())
        {
            var filter = DependencyResolver.Current.GetService<MyAuthorizationFilter>();
            yield return new Filter(filter, FilterScope.Global);
        }

        yield break;
    }
}

それはあなたのに登録されますApplication_Start

FilterProviders.Providers.Add(new MyFilterProvider());
于 2013-05-23T08:25:35.273 に答える