在 ASP.Net MVC 中动态地将角色映射到控制器

发布于 2024-09-24 13:36:00 字数 429 浏览 4 评论 0原文

我目前正在 MVC 应用程序的过滤器中对授权角色进行硬编码,如下所示:

[Authorize(Roles = "Administrator,Manager")]

我希望最终有一种方法将角色映射到每个控制器,以便站点管理员可以处理分配哪些角色可以执行每组操作行动。

string roles = DoSomethingToGetAllowableRoles(controllerName);

[Authorize(Roles = roles)]

我想象我需要一个数据库表来以某种方式保存每个控制器的列表,然后另一个表将控制器映射到角色。我想要的是一个页面,我可以在其中列出每个控制器,然后有一组复选框列出适用于该控制器的每个角色。

任何人都有一个例子或者可以引导我朝实现这一目标的方向前进吗?

I am currently hard coding the authorized roles in the filter in my MVC applications like so:

[Authorize(Roles = "Administrator,Manager")]

I'd like to eventually have a way to map the roles to each controller, so that the site admin can handle assigning what roles can perform each set of actions.

string roles = DoSomethingToGetAllowableRoles(controllerName);

[Authorize(Roles = roles)]

I'm imagining that I need to have a database table that somehow keeps a listing of each controller, and then another table mapping the controllers to the roles. What I'd like is a page where I can list out each controller and then have a set of check boxes that lists each role that applies to that controller.

Anyone have an example or can lead me in a direction that will accomplish this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傲鸠 2024-10-01 13:36:00

您将需要编写自己的授权过滤器(可能通过扩展内置过滤器)。

原因是您无法像这样动态分配属性参数。

您不需要弄乱 MVC 源代码 - 您只需创建一个继承自 System.Web.Mvc.AuthrorizeAttribute 的类,覆盖 AuthorizeCore,然后使用您的属性代替默认属性:

public class CustomAuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // Put your custom logic here, returning true for success and false for failure,
        // or return base.AuthorizeCore(httpContext) to defer to the base implementation
    }
}

You're going to need to write your own authorization filter (probably by extending the built in one).

The reason for this is that you can't assign attribute parameters dynamically like that.

You won't need to mess with the MVC source code - you just need to create a class which inherits from System.Web.Mvc.AuthrorizeAttribute, override AuthorizeCore, and then use your attribute in place of the default:

public class CustomAuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // Put your custom logic here, returning true for success and false for failure,
        // or return base.AuthorizeCore(httpContext) to defer to the base implementation
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文