6

我已经3个模型[用户,角色,和的UserRole]基于角色的授权与标准清单

 
Use {ID [PK], Name, Email, Password, .....} 
Role {ID [PK], Name, Description, .......} 
UserRole {UserID [FK], RoleID [FK]} 

考虑,使用[授权]上控制器基于角色的授权属性指定用户必须在管理员角色来访问类

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

这是好的,我需要的是任何控制器动作,

有什么办法,以我的角色集合分配到[Authoriz e]属性?例如

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

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

1+,投票,很好的问题.... –

回答

1

好吧,有两个问题。

首先,您不能使用List作为Attribute的参数。您可以改为使用数组。 http://msdn.microsoft.com/fr-fr/library/ms177221%28v=vs.100%29.aspx

其次,在编译时必须知道属性参数的值:只有在运行时才能知道列表的内容。

你会得到这样的消息:

的属性参数必须是常量表达式的typeof属性参数类型

解决方案是创建的表达 或数组创建表达式一个新的授权属性(继承自AuthorizeAttribute)和覆盖AuthorizedCore

一个示例(您可以适应您的问题)可以发现here

1

是的。在global.asax中

  1. 覆盖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; 
    } 
} 
+0

你可以建议我一些教程或博客,所以我可以去一步一步 –

+0

我添加了一个例子 – jgauffin

+0

老兄,对不起,我很新,你能否给我提供一些更详细的例子?以及这可以如何应用于控制器的[授权]属性? –