使用AuthorizeAttribute进行角色授权,但不将角色值硬编码

5

是否有可能添加角色,但不像硬编码的值一样:

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

我希望能够从数据库或配置文件中检索这些角色,这样如果我需要添加/删除控制器操作的角色,则无需重新构建应用程序。
我知道可以使用枚举来实现... http://www.vivienchevallier.com/Articles/create-a-custom-authorizeattribute-that-accepts-parameters-of-type-enum 但即使如此,它对我的需求仍不够灵活;它仍然有点像硬编码,尽管它更加清晰。
2个回答

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

我希望能对您有所帮助。

IActionRoleConfigService和IUserRoleService属于哪个命名空间? - zeb ula
可以添加命名空间,因为Mvc和WebApi之间存在歧义。谢谢。而AuthorizationContext有许多命名空间。 :< - granadaCoder
@granadaCoder 如果你有MVC项目,可以使用System.Web.Mvc类。 - David Levin

3

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

您需要实现自定义角色提供程序。请参阅在MSDN上实现角色提供程序

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

}

明确一点,在我的情况下,群组将是角色,而角色将是函数。因此,使用我的术语,每个角色将具有许多函数,一对多的关系:角色(1)-功能(*)。我的计划是像您在“CreateUser”属性中所做的那样使用操作名称。在这种情况下,任何具有创建用户功能的角色都将被允许。 - zeb ula

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接