2012-01-28 38 views
4

是否有可能添加的角色而不是硬编码值,如:AuthorizeAttribute使用角色而不是硬编码的角色值

[Authorize(Roles="members, admin")] 

我想从数据库中检索或配置文件中的这些角色如果我需要为控制器操作添加/删除角色,我不需要重新构建应用程序。

我知道它可以做的枚举... http://www.vivienchevallier.com/Articles/create-a-custom-authorizeattribute-that-accepts-parameters-of-type-enum 但即使如此,仍然不够灵活,我的需要;尽管它更干净,但它仍然有点硬编码。

回答

3

一个解决方案是创建一个名为“Group”的中间实体,用户被添加到组中(例如:Admin,Support)并且组具有角色集合。 (例如:创建用户)。这样你可以硬编码角色并配置用户和组之间的关系。

您需要实现一个自定义角色提供程序。通过Implementing a Role Provider On MSDN

[Authorize(Roles="CreateUser")] 
public ActionResult Create() 
{ 

} 
+0

要明确,在我的情况下,组将是角色和角色将是功能。因此,使用我的术语,每个角色都有许多功能,一对多的关系:角色(1) - 功能(*)。我的计划是使用Action Name,就像你在'CreateUser'属性中完成的一样。在这种情况下,任何具有创建用户功能的角色都将被允许。 – 2012-01-28 19:11:11

+0

@zebula这是正确的。 – Eranga 2012-01-29 00:22:51

9

去,你可以创建自定义的授权属性,将比较用户角色和角色从配置。

public class ConfigAuthorizationAttribute: AuthorizeAttribute 
{ 
    private readonly IActionRoleConfigService configService; 
    private readonly IUserRoleService roleService; 

    private string actionName; 

    public ConfigAuthorizationAttribute() 
    { 
     configService = new ActionRoleConfigService(); 
     roleService = new UserRoleService(); 
    } 

    protected override void OnAuthorization(AuthorizationContext filterContext) 
    { 
     actionName = filterContext.ActionDescription.ActionName; 
     base.OnAuthorization(filterContext); 
    } 

    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     var availableRoles = configService.GetActionRoles(actionName); // return list of strings 
     var userName = httpContext.User.Identity.Name; 
     var userRoles = roleService.GetUserRoles(userName); // return list of strings 
     return availableRoles.Any(x => userRoles.Contains(x)); 
    } 
} 

我希望它可以帮助你。

+0

IActionRoleConfigService和IUserRoleService中有哪些命名空间? – 2012-02-03 01:51:29

+0

这是您自己的服务 – 2012-02-03 09:50:58

+0

您可以添加命名空间,因为Mvc和WebApi之间存在歧义。谢谢。 AuthorizationContext有许多命名空间。 :< – granadaCoder 2015-08-05 20:35:45

相关问题