【问题标题】:AuthorizeAttribute with Roles but not hard-coding the Role valuesAuthorizeAttribute 与角色但不硬编码角色值
【发布时间】:2012-02-21 01:32:26
【问题描述】:

是否可以添加角色但不能硬编码值,例如:

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

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

我知道使用枚举可以做到... http://www.vivienchevallier.com/Articles/create-a-custom-authorizeattribute-that-accepts-parameters-of-type-enum 但即使这样仍然不够灵活,无法满足我的需求;尽管它更简洁,但它仍然有点硬编码。

【问题讨论】:

    标签: asp.net-mvc-3 authorization security-roles


    【解决方案1】:

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

    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));
        }
    }
    

    希望对你有帮助。

    【讨论】:

    • IActionRoleConfigService 和 IUserRoleService 在哪些命名空间?
    • 你能添加命名空间吗,因为 Mvc 和 WebApi 之间存在歧义。谢谢。 AuthorizationContext 有很多命名空间。 :
    • @granadaCoder 使用 System.Web.Mvc 类,如果你有 MVC 项目。
    【解决方案2】:

    一种解决方案是创建一个名为“组”的中间实体,其中将用户添加到组(例如:管理员、支持),并且组具有一组角色。 (例如:创建用户)。这样您就可以对角色进行硬编码并配置用户和组之间的关系。

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

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

    【讨论】:

    • 明确地说,在我的情况下,组是角色,角色是函数。因此,使用我的术语,每个角色将有许多功能,一对多的关系:角色(1) - 功能(*)。我的计划是使用您在“CreateUser”属性中所做的操作名称。在这种情况下,任何具有创建用户功能的角色都将被允许。
    猜你喜欢
    • 2021-08-18
    • 2012-09-02
    • 2011-05-01
    • 2011-11-10
    • 2014-11-02
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    相关资源
    最近更新 更多