对所有控制器操作强制执行操作过滤器 (C# / ASP.NET MVC)

发布于 2024-08-03 08:22:20 字数 217 浏览 12 评论 0原文

我创建了一个新的操作过滤器(属性,类似于 [Authorize]),它根据会话值授权对控制器操作的访问。但是,我基本上用该属性装饰我的所有控制器操作(除了极少数)。

因此,我认为最好让该操作过滤器始终执行除非在我将 [ExemptFromAuthorize] 属性附加到控制器操作的情况下? (也许通过继承到我自己的控制器类?)

我怎样才能做到这一点?

I made a new action filter (attribute, similar to [Authorize]) which authorizes access to a controller action based on a session value. However, I'm basically decorating all my controller actions with that attribute (with the exception of very few).

So, I thought it would be better to have that Action Filter always executed except in cases where I attach an [ExemptFromAuthorize] attribute to a controller action? (Maybe via inheriting to my own Controller class?)

How can I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

尴尬癌患者 2024-08-10 08:22:20

使用 jeef3 的答案,我想出了这个。它可以使用更多的错误检查和鲁棒性,例如多个分隔操作,但总体思路是有效的。

在您的具体情况下,您可以测试会话值并决定也退出授权。

public class AuthorizeWithExemptionsAttribute : AuthorizeAttribute
{
    public string Exemption { get; set; }
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext.RouteData.GetRequiredString("action") == Exemption)
            return;

        base.OnAuthorization(filterContext);
    }

}

用法:

[AuthorizeWithExemptions(Roles="admin", ExemptAction="Index")]
public class AdminController : Controller
...

Running with jeef3's answer, I came up with this. It could use more error checking and robustness like multiple delimited actions, but the general idea works.

In your specific case, you could test for the session value and decide to return out of the authorization also.

public class AuthorizeWithExemptionsAttribute : AuthorizeAttribute
{
    public string Exemption { get; set; }
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext.RouteData.GetRequiredString("action") == Exemption)
            return;

        base.OnAuthorization(filterContext);
    }

}

Usage:

[AuthorizeWithExemptions(Roles="admin", ExemptAction="Index")]
public class AdminController : Controller
...
伤感在游骋 2024-08-10 08:22:20

查看我关于 codeproject 的文章 -

http://www.codeproject.com/KB/ web-security/AuthorizeWithExemptions.aspx

在本文中,我将向您提供一个保护 ASP.NET MVC 应用程序控制器的解决方案,确保除您定义为不安全的操作之外的所有操作均受到保护。

代码中的截图:

public override void OnAuthorization(AuthorizationContext filterContext)
{
    ActionDescriptor action = filterContext.ActionDescriptor;
    bool IsUnsecured = action.GetCustomAttributes(
                         typeof(UnsecuredActionAttribute), true).Count() > 0;

    //If doesn't have UnsecuredActionAttribute - then do the authorization
    filterContext.HttpContext.SkipAuthorization = IsUnsecured;

    base.OnAuthorization(filterContext);
}

Check out my article on codeproject -

http://www.codeproject.com/KB/web-security/AuthorizeWithExemptions.aspx

In this article, I'll provide you with a solution for securing ASP.NET MVC application's controllers in a way that all the actions are secured except those you define as unsecure.

snipper from the code:

public override void OnAuthorization(AuthorizationContext filterContext)
{
    ActionDescriptor action = filterContext.ActionDescriptor;
    bool IsUnsecured = action.GetCustomAttributes(
                         typeof(UnsecuredActionAttribute), true).Count() > 0;

    //If doesn't have UnsecuredActionAttribute - then do the authorization
    filterContext.HttpContext.SkipAuthorization = IsUnsecured;

    base.OnAuthorization(filterContext);
}
写给空气的情书 2024-08-10 08:22:20

我知道这个问题已经过时了,但无论如何..如果您希望将过滤器应用于所有操作,只需将以下行添加到 Global.asax 中:

protected void Application_Start()
{
    // your code here and then
    RegisterGlobalFilters(GlobalFilters.Filters);
}    

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new MyActionFilterAttribute());
}

在操作过滤器中,您可以通过以下方式检查操作是否具有任何其他属性:

public void OnActionExecuting(ActionExecutingContext filterContext)
{
    if (filterContext.ActionDescriptor.IsDefined(typeof(AnotherActionAttribute), false))
    {
        // do what you want to do
    }
}

I understand the question is pretty outdated but anyway.. If you wish to apply filter to all actions just add following lines into Global.asax:

protected void Application_Start()
{
    // your code here and then
    RegisterGlobalFilters(GlobalFilters.Filters);
}    

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new MyActionFilterAttribute());
}

And in action filter you can just check if action has any other attributes in following way:

public void OnActionExecuting(ActionExecutingContext filterContext)
{
    if (filterContext.ActionDescriptor.IsDefined(typeof(AnotherActionAttribute), false))
    {
        // do what you want to do
    }
}
感性 2024-08-10 08:22:20

也许尝试将 Except 属性添加到您的第一个属性中?

[MyAuthenticate(Exempt="View")]
public class MyController : Controller
{
    public ActionResult Edit()
    {
        // Protected
    }

    public ActionResult View()
    {
        // Accessible by all
    }
}

Maybe try and add an Except property to your first attribute?

[MyAuthenticate(Exempt="View")]
public class MyController : Controller
{
    public ActionResult Edit()
    {
        // Protected
    }

    public ActionResult View()
    {
        // Accessible by all
    }
}
枕头说它不想醒 2024-08-10 08:22:20

您可以将该属性添加到类中,以使其应用于该类中的所有方法。

[Authenticate]
public class AccountController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

我不知道如何从类级属性中排除特定方法。也许对未经身份验证的请求使用单独的控制器?

You can add the attribute to the class to have it apply to all methods in that class

[Authenticate]
public class AccountController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

I don't know how to exclude a specific method from a class-level attribute. Maybe use a separate controller for unauthenticated requests?

独﹏钓一江月 2024-08-10 08:22:20

对于 2013 年以后阅读本文的人来说,MVC4 现在支持使用
[允许匿名]

您可以在控制器上设置“授权”,然后在“允许匿名”上设置
您不想授权的任何功能。

示例:

[授权]
公共类 HomeController :控制器 {

<前><代码>[AllowAnonymous]
公共 ActionResult Index()
{

}

}

这适用于自定义 [MyAuthorize] 过滤器还是仅适用于 [Authorize]

For anyone reading this in 2013+, MVC4 now supports the use of
[AllowAnonymous]

You can put Authorize on the controller, and then Allow Anonymous on
any functions you do not want to authorize.

Example:

[Authorize]
public class HomeController : Controller {

[AllowAnonymous]
public ActionResult Index()
{

} 

}

Would this work with a custom [MyAuthorize] filter or does it only work with [Authorize]

傲世九天 2024-08-10 08:22:20

对于 2013 年以后阅读本文的任何人,MVC4 现在支持使用 [AllowAnonymous]

您可以在控制器上进行授权,然后对您不想授权的任何功能进行允许匿名。

例子:

[Authorize]
public class HomeController : Controller
{

    [AllowAnonymous]
    public ActionResult Index()
    {

    }
}

For anyone reading this in 2013+, MVC4 now supports the use of [AllowAnonymous]

You can put Authorize on the controller, and then Allow Anonymous on any functions you do not want to authorize.

Example:

[Authorize]
public class HomeController : Controller
{

    [AllowAnonymous]
    public ActionResult Index()
    {

    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文