5

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

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

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

我知道使用枚举可以做到... http://www.vivienchevallier.com/Articles/create-a-custom-authorizeattribute-that-accepts-parameters-of-type-enum 但即使这样仍然不灵活足以满足我的需要;它仍然是一个硬代码,即使它更干净。

4

2 回答 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));
    }
}

我希望它对你有帮助。

于 2012-01-28T20:03:21.393 回答
3

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

您需要实现自定义角色提供者。通过在 MSDN 上实现角色提供程序

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

}
于 2012-01-28T08:26:36.757 回答