简体   繁体   English

如果我想使用ASP.NET MVC4创建ApiKey受限资源,我应该使用IAuthorizationFilter吗?

[英]Should I be using an IAuthorizationFilter if I wish to create an ApiKey restricted resource with ASP.NET MVC4?

I have a few simple routes which I wish to restrict via a simple querystring param. 我有一些简单的路由,我希望通过一个简单的查询字符串参数进行限制。 If the key is incorrect or not provided, then I wish to throw a NotAuthorizedException . 如果密钥不正确或未提供,那么我希望抛出NotAuthorizedException

Please don't suggest I use WebApi or the equiv - I can't just yet in this scenario. 请不要建议我使用WebApi或等效 - 我不能在这种情况下使用。

So i'm not sure if I should be implementing an IAuthorizationFilter or implementing an IActionFilter or even something else. 所以我不确定我是应该实现IAuthorizationFilter还是实现IActionFilter甚至是其他东西。

My code logic? 我的代码逻辑?

  • Check querystring for key. 检查查询字符串是否有关键。
  • Check my RavenDb (repository) for a user with that key/value. 检查我的RavenDb(存储库)以查找具有该键/值的用户。

If they fail any of those checks, then throw the NotAuthorizedException . 如果它们未通过任何检查,则抛出NotAuthorizedException

I'm assuming I would then decorate a my action method with this filter. 我假设我会用这个过滤器装饰我的动作方法。 I'm also assuming i would need to pass in my repository into this action method also? 我还假设我需要将我的存储库传递给这个动作方法吗?

Any suggestions please? 有什么建议吗?

So i'm not sure if I should be implementing an IAuthorizationFilter or implementing an IActionFilter or even something else. 所以我不确定我是应该实现IAuthorizationFilter还是实现IActionFilter甚至是其他东西。

You should be implementing an IAuthorizationFilter : 您应该实现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();
    }
}

And if you wanted to use dependency injection into your custom action filter you could take a look at the following article in which you could implement a custom filter provider ( IFilterProvider ). 如果您想在自定义操作过滤器中使用依赖项注入,您可以查看following article ,您可以在其中实现自定义过滤器提供程序( IFilterProvider )。 You could have a marked attribute which you may use on controller actions and then have this custom filter provider simply look whether the action is decorated with this marker attribute and apply the custom authorization filter. 您可以使用可在控制器操作上使用的标记属性,然后让此自定义过滤器提供程序只查看操作是否使用此标记属性进行修饰并应用自定义授权过滤器。

For example: 例如:

public class MyAuthorizeAttribute: Attribute
{

}

and your authorization filter will only implement the IAuthorizationFilter , it won't be a FilterAttribute : 并且您的授权过滤器只会实现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();
    }
}

and then you will have the custom filter provider: 然后你将拥有自定义过滤器提供程序:

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

that will be registered in your Application_Start : 将在您的Application_Start注册:

FilterProviders.Providers.Add(new MyFilterProvider());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用jquery ajax在ASp.net MVC4中创建级联文本框 - How do i create cascading textboxes in ASp.net mvc4 using jquery ajax 在SignalR和ASP.NET MVC4之间同步客户端状态(或者甚至应该使用SignalR?) - Synchronizing client state between SignalR and ASP.NET MVC4 (or should I even use SignalR?) 当我尝试使用 ASP.NET 核心标识创建新用户时,为什么我的 ApiKey 变量位于 null 中? - Why can it be that my ApiKey variable is in null when I try to create a new user using ASP.NET Core Identity? 如何在asp.net MVC4中使用路由? - how can i use routing in asp.net MVC4? 我如何使用 datapost 将参数从 jqgrid 传递到 controller(使用 MVC4 和 asp.net) - how can i pass parameter from jqgrid to controller with datapost (using MVC4 and asp.net ) 我会在哪里使用mvc4和EF在asp.net中哈希密码? - Where would I hash a password in asp.net using mvc4 and EF? 如何使ASP.NET MVC IAuthorizationFilter尊重IgnoreRoute的 - How to get ASP.NET MVC IAuthorizationFilter to respect IgnoreRoute's ASP.NET IAuthorizationFilter OnAuthorization - ASP.NET IAuthorizationFilter OnAuthorization 迁移不如我所愿... Asp.net EntityFramework - Migration not working as I wish… Asp.net EntityFramework Asp.net MVC4,C#创建对象实例 - Asp.net MVC4, C# Create object instance
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM