【问题标题】:Access by roles at controller level控制器级别的角色访问
【发布时间】:2015-03-26 18:31:45
【问题描述】:

MVC 是否可以允许 1 个角色访问整个控制器除了另一个角色可以访问一个或几个方法?

除了Method3之外的所有方法都属于员工的地方,客户和员工都可以访问。如下所示:

    [Authorize(Roles = "staff")]
    public class StaffController : Controller
    {
        public StaffController()
        {
        }
        public ActionResult Method1()
        {
        }
        public ActionResult Method2()
        {
        }
        [Authorize(Roles = "staff, customer")]
        public ActionResult Method3()
        {
        }
    }

或者其他所有人都属于员工的场景,除了 Method3 之外,它只能由客户访问,如下所示:

    [Authorize(Roles = "staff")]
    public class StaffController : Controller
    {
        public StaffController()
        {
        }
        public ActionResult Method1()
        {
        }
        public ActionResult Method2()
        {
        }
        [Authorize(Roles = "customer")]
        public ActionResult Method3()
        {
        }
    }

但是,上述方法不起作用。在这两种情况下,客户端仍然无法访问 Method3。

非常感谢任何帮助!

【问题讨论】:

    标签: model-view-controller controller authorization


    【解决方案1】:

    我怀疑它首先检查控制器授权,因此永远没有机会检查其授权的具体操作。

    一种解决方案是在类级别授权这两个角色,并将特定方法的访问权限限制为仅staff

    例如

    [Authorize(Roles="staff,customer")]
    public class StaffController : Controller
    {
        [Authorize(Roles="staff")]
        public StaffController()
        {
        }
        [Authorize(Roles="staff")]
        public ActionResult Method1()
        {
        }
        [Authorize(Roles="staff")]
        public ActionResult Method2()
        {
        }
        public ActionResult Method3()
        {
        }
    }
    

    另一种选择是Restrict(即与Authorize 相反)使用此答案ASP.NET MVC: Opposite of [Authorise] 上的自定义属性之类的东西 但正如他们提到的那样,这违反了 MVC 安全性的“默认拒绝”原则。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-04
      • 1970-01-01
      • 2018-02-05
      • 1970-01-01
      • 2016-04-30
      • 2010-09-11
      • 1970-01-01
      • 2013-05-08
      相关资源
      最近更新 更多