2012-01-28 98 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

相關問題