【问题标题】:Access profiles using attributes使用属性访问配置文件
【发布时间】:2014-06-24 13:05:42
【问题描述】:

在我的网站上,我有具有不同访问权限级别的不同页面。通常,我会使用一些东西:

if(!user.IsAdministrator)
    return RedirectToAction("AccessDenied", "Security");

但我意识到这将我与我预先建立的安全级别联系在一起;我实际上想要的是一个完全可定制的访问方案。

我想到的一个解决方案是在我想要限制访问的操作中设置一些属性,然后检索它们的放置位置。我对属性(至少是自定义属性)有点缺乏经验,虽然我知道如何列出所有被标记的操作,但我仍在努力想出一种方法来检查正确的访问权限并拒绝访问。

关于这个主题有什么亮点吗?我也很想知道是否有任何标准做法来处理这个问题。

【问题讨论】:

    标签: c# asp.net custom-attributes


    【解决方案1】:

    通常在 ASP.NET MVC 中 Authorize 属性可用于此目的。

    您可以从中派生并覆盖 AuthorizeCore 方法以满足您的需求。然后,您可以使用此属性标记 MVC 操作或整个 MVC 控制器。或者更好的是,您可以将其配置为全局过滤器,因此它将自动为所有控制器启用。然后可以使用 AllowAnonymous 属性标记您不想保护的操作:http://blogs.msdn.com/b/rickandy/archive/2012/03/23/securing-your-asp-net-mvc-4-app-and-the-new-allowanonymous-attribute.aspx

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            if (filters != null)
            {
                filters.Add(new CustomAuthorizeAttribute());
            }
        }
    
    
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public sealed class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            //your code here
        }
    

    这是一个已经讨论过属性的帖子 ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

    您可以在互联网上找到更多关于此主题的文章。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-22
      • 2017-10-03
      • 1970-01-01
      • 2017-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      相关资源
      最近更新 更多