是否可以添加角色但不能对值进行硬编码,例如:
[Authorize(Roles="members, admin")]
我想从数据库或配置文件中检索这些角色,如果我需要为控制器操作添加/删除角色,则不需要重建应用程序。
我知道用枚举可以做到......http://www.vivienchevallier.com/Articles/create-a-custom-authorizeattribute-that-accepts-parameters-of-type-enum但即使这样仍然不够灵活以满足我的需求;尽管它更干净,但它仍然有点硬编码。
您可以创建自定义授权属性,该属性将比较用户角色和配置中的角色。
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));
}
}
我希望它对你有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)