AuthorizeAttribute。为控制器授予对不同角色的某些操作的访问权限

时间:2018-06-16 11:45:24

标签: asp.net-mvc authorization

我的应用程序中有两个角色:AdminContentMaker。管理员具有完全访问权限,ContentMaker可以创建\编辑文章。一个用户有一个角色(一对一)。 虽然我对使用AuthorizeAttribute修饰的所有内容(包括管理文章)只有一个AdminController。我只想授予访问权限,以便在AdminController中编辑ContentMaker的文章。问题是内容制作者不是管理员,因此他无法访问AdminController。是否可以扩展AuthorizeAttribute以允许此行为?这就是我想要的:

//only Admin can access this controller
[Authorize(Roles = ConstantsWeb.Database.AdminRoleName)]
public partial class AdminController : Controller
{
    //ContentMaker has no access here
    public ActionResult SomeAdminStuffAction()
    {
        //code
    }

    //ContentMaker only has access here, although he is not Admin
    [Authorize(Roles = ConstantsWeb.Database.ContentMakerRoleName)]
    public ActionResult EditArticle(int id)
    {
        //code
    }
}

1 个答案:

答案 0 :(得分:0)

这是简单的解决方案。由于ASP.NET MVC 5是OverrideAuthorization属性。它允许覆盖控制器中任何操作的访问权限。您需要放置OverrideAuthorization属性和另一个Authorize属性。像这样:

//only Admin can access this controller
[Authorize(Roles = ConstantsWeb.Database.AdminRoleName)]
public partial class AdminController : Controller
{
    //ContentMaker has no access here
    public ActionResult SomeAdminStuffAction()
    {
        //code
    }

    //ContentMaker only has access here, although he is not Admin
    [OverrideAuthorization]
    [Authorize(Roles = ConstantsWeb.Database.AdminRoleName + "," + ConstantsWeb.Database.ContentMakerRoleName)]
    public ActionResult EditArticle(int id)
    {
        //code
    }
}