动态分配控制器操作权限给asp.net MVC中的角色 [英] Dynamically assign controller action permissions to roles in asp.net MVC

查看:171
本文介绍了动态分配控制器操作权限给asp.net MVC中的角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在asp.net mvc 5上工作.我想动态地将控制器的操作方法的权限分配给角色,而无需在Authorize属性中硬性地填充角色.

I am working on asp.net mvc 5. I want to assign permissions of controllers' action methods to roles dynamically without hard conding the roles in Authorize attribute.

这是场景- 在我的项目中,我有四个角色-学生,老师,程序主任和管理员. 我希望管理员可以随时更改每个角色的可访问性.我不想在控制器的每个操作名称之前用角色名称硬编码authorize属性,因为管理员将无法更改每个角色的权限.

Here is the scenario - In my project, I have four roles - Student, Teacher, Program Officer and Admin. I want that admin can change the accessability of each role whenever he wishes. I do not want to hard code the authorize attribute with role names before every action name of controller because admin will not then be able to change the permissions of each role.

我想创建一个页面,其中控制器的每种操作方法都将列为复选框,并且管理员可以为角色选择操作复选框.然后,该角色用户将获得这些操作方法的可访问性.

I want to create a page where every action method of controller will be listed as checkbox and admin can select action checkboxes for a role. Then that role users will get accessability of those action methods.

在这里,我要使用户界面如下所示-

Here I want to make the UI as following -

任何人都可以通过提供任何建议,代码或链接来帮助我做到这一点吗?

Can anyone please help me to do this by giving any suggestion or code or link?

推荐答案

想象一下,您有服务可以根据控制器和操作名称返回角色数组,如下所示:

Imagine you have service which returns array of roles based on controller and action name like this:

public class RoleProvider
{
    public string[] Get(string controller, string action)
    {
        // get your roles based on the controller and the action name 
        // wherever you want such as db
        // I hardcoded for the sake of simplicity 
        return new string[]{"Student", "Teacher"};
    }
}

现在,您可以编写自己的授权属性,如下所示:

Now you can write your own authorization attribute something like this:

public class DynamicRoleAuthorizeAttribute: AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var controller = httpContext.Request.RequestContext
            .RouteData.GetRequiredString("controller");
        var action = httpContext.Request.RequestContext
            .RouteData.GetRequiredString("action");
        // feed the roles here
        Roles = string.Join("," ,_rolesProvider.Get(controller, action));
        return base.AuthorizeCore(httpContext);
    }
}

现在使用您的自定义授权属性,而不是像这样的较早的属性:

Now use your custom authorization attribute instead of older one like this:

[DynamicRoleAuthorize]
public ActionResult MyAction()
{

}

这篇关于动态分配控制器操作权限给asp.net MVC中的角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆