gpt4 book ai didi

ASP.NET MVC3 角色和权限管理 -> 使用运行时权限分配

转载 作者:行者123 更新时间:2023-12-03 13:21:03 25 4
gpt4 key购买 nike

ASP.NET MVC 允许用户在设计时为功能(即操作)分配权限,就像这样。

[Authorize(Roles = "Administrator,ContentEditor")]
public ActionResult Foo()
{
return View();
}

要实际检查权限,可以在(Razor) View 中使用以下语句:
@if (User.IsInRole("ContentEditor"))
{
<div>This will be visible only to users in the ContentEditor role.</div>
}

这种方法的问题是必须在设计时设置所有权限并将其分配为属性。 (属性是与 DLL 一起编译的,因此我目前知道没有机制可以在运行时应用属性(以允许其他权限),例如 [Authorize(Roles = "Administrator,ContentEditor")]。

在我们的用例中,客户端需要能够在部署后更改哪些用户拥有哪些权限。

例如,客户端可能希望允许 ContentEditor 中的用户角色编辑特定类型的某些内容。可能不允许用户编辑查找表值,但现在客户端希望允许此操作,而不授予用户下一个更高角色的所有权限。相反,客户端只是想修改用户当前角色可用的权限。

有哪些策略可用于允许在属性之外(如在数据库中)定义 MVC Controller / View /操作的权限并在运行时评估和应用?

如果可能,我们非常希望尽可能地坚持使用 ASP.NET 成员资格和角色提供程序功能,以便我们可以继续利用它提供的其他好处。

提前感谢您的任何想法或见解。

最佳答案

What options are strategies are available to allow permissions on MVC Controllers/Views/Actions to be defined outside of attributes (as in a database) and evaluated and applied at runtime?



自定义 Authorize 属性是实现此目的的一种可能性:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
Roles = ... go ahead and fetch those roles dynamically from wherever they are stored
return base.AuthorizeCore(httpContext);
}
}

进而:
[MyAuthorize]
public ActionResult Foo()
{
return View();
}

关于ASP.NET MVC3 角色和权限管理 -> 使用运行时权限分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7286379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com