具有角色的AuthorizeAttribute但不对角色值进行硬编码

zeb*_*ula 4 authorization security-roles asp.net-mvc-3

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

[Authorize(Roles="members, admin")]
Run Code Online (Sandbox Code Playgroud)

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

我知道它可以用枚举来完成... http://www.vivienchevallier.com/Articles/create-a-custom-authorizeattribute-that-accepts-parameters-of-type-enum 但即使这仍然不灵活足以满足我的需求; 它仍然有点硬编码,即使它更干净.

Evg*_*vin 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));
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望它对你有所帮助.


Era*_*nga 3

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

您需要实现一个自定义角色提供程序。在 MSDN 上完成实施角色提供程序

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

}
Run Code Online (Sandbox Code Playgroud)