0

我正在考虑在我当前的站点中创建一个安全修剪的 MenuLinks,并想知道 MVC4 中最简单的方法是确定当前用户是否可以仅使用控制器名称和操作名称访问给定的控制器和操作。

我遇到了几个问题\答案,其中“解决方案”的链接断开了,还有几个针对 MVC 的早期版本,看起来很复杂。我想如果我必须创建给定控制器的实例,获取授权属性然后手动进行安全检查,但我真的希望 MVC4 中可能有更简单的方法!:)

本质上,我正在寻找关于如何UserHasAccessTo在以下实现“”的等效项或建议:

    public static MvcHtmlString SecurityTrimmedActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName)
    {
        if(UserHasAccessTo(actionName, controllerName))
            return htmlHelper.ActionLink(linkText, actionName, controllerName);
        return MvcHtmlString.Empty;
    }
4

1 回答 1

0

以下是一种简单安全的方法

  1. 定义一个继承自 AuthorizeAttribute 并覆盖 AuthorizeCore 的属性

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,
                             Inherited = true, AllowMultiple = true)]
        internal sealed class MyAttribute : AuthorizeAttribute
        {
            protected override bool AuthorizeCore(HttpContextBase httpContext)
            {
                var username = httpContext.User.Identity.Name;
    
                if (string.IsNullOrEmpty(username))
                    return false;
    
                return UserHasAccessTo(username, ActionName, ControllerName);
            }
    
            public bool ActionName { get; set; }
    
            public bool ControllerName { get; set; }
        }
    
  2. 覆盖 HandleUnauthorizedRequest

    protected override void 
                 HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = string.Empty;
    }
    
  3. 将属性应用于您的方法或类

于 2013-09-05T03:47:03.183 回答