【问题标题】:Role-based Authorization with Model List使用模型列表进行基于角色的授权
【发布时间】:2012-08-28 23:54:08
【问题描述】:

我有 3 个模型 [User、Role 和 UserRole]

使用 {ID [PK]、姓名、电子邮件、密码、.....} 角色{ID [PK],名称,描述,.......} 用户角色 {用户 ID [FK],角色 ID [FK]}

考虑一下,控制器上基于角色的授权使用 [Authorize] 属性指定用户必须是管理员角色才能访问类中的任何控制器操作

[Authorize(Roles = "Administrator")]
public class PageController : Controller
{
    // Controller code here
}

这很好,我需要的是,

有没有办法将我的角色集合分配给 [Authorize] 属性?例如

我将从登录用户中获取分配的角色并将其存储在列表中。是否可以将此列表分配给 [Authorize] 属性?如下所示:

[Authorize(Roles = MyDynamicallyLoadedList)]
public class PageController : Controller
{
    // Controller code here
}

【问题讨论】:

  • 1+,投票,好问题....

标签: asp.net-mvc-3 authorization authorize-attribute role-based


【解决方案1】:

是的。

  1. 覆盖 global.asax 中的 PostAuthenticateRequest
  2. 从数据库加载角色
  3. 创建一个新的GenericPrincipal
  4. 将主体分配给Thread.CurrentPrincipalHttpContext.Current.User

例子:

protected void Application_OnPostAuthenticateRequest(object sender, EventArgs e)
{
    if (User.Identity.IsAuthenticated)
    {
        string[] rolelist = GetRoleListForUserFromAPI(User.Identity.Name);
        HttpContext.Current.User = new GenericPrincipal(User.Identity, rolelist);
        Thread.CurrentPrincipal = HttpContext.Current.User;
    }
}

【讨论】:

  • 你能给我推荐一些教程或博客,这样我就可以一步一步地去
  • 老兄,对不起,我对这个很陌生,你能给我提供更详细的例子吗?以及如何将其应用于控制器的 [Authorize] 属性?
  • 上面的例子加载了当前用户拥有的所有角色。属性中指定的角色指定操作所需的角色。它们是两个非常不同的东西。目前尚不清楚您真正在寻找什么。
【解决方案2】:

嗯,有两个问题。

首先,您不能将列表用作属性的参数。您可以改用数组。 http://msdn.microsoft.com/fr-fr/library/ms177221%28v=vs.100%29.aspx

第二,attributes 参数的值必须在编译时知道:你的列表的内容只有在运行时才知道。

您会收到如下消息:

属性参数必须是常量表达式,typeof 表达式 或属性参数类型的数组创建表达式

解决方案是创建一个新的 Authorization 属性(继承自 AuthorizeAttribute),并覆盖 AuthorizedCore

可以找到一个例子(你可以适应你的问题)here

【讨论】:

    猜你喜欢
    • 2016-07-20
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    相关资源
    最近更新 更多