问题描述
是否有可能添加的角色而不是硬编码值,如:
Is it possible to add the Roles but not hard-coding the values like:
[Authorize(Roles="members, admin")]
我想在那里我不会需要重新构建应用程序,如果我需要添加/删除角色的控制器动作从数据库中检索或配置文件中的这些角色。
I would like to retrieve these roles from a database or configuration file where I wouldn't need to rebuild the application if I needed to add/remove Roles for a Controller Action.
我知道用它可以做枚举...
http://www.vivienchevallier.com/Articles/create-a-custom-authorizeattribute-that-accepts-parameters-of-type-enum
但即使这样仍不能满足我的需求足够的灵活性;它仍然是一个有点硬code的,即使它是清洁的。
I know with the enums it can be done...http://www.vivienchevallier.com/Articles/create-a-custom-authorizeattribute-that-accepts-parameters-of-type-enumbut even this is still not flexible enough for my needs; it's still somewhat of a hard-code, even though it is cleaner.
推荐答案
您可以创建自定义的授权属性,这会比较用户角色和角色从配置。
You can create your custom authorization attribute, that will compare user roles and roles from your configuration.
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));
}
}
我希望它可以帮助你。
I hope it helps you.
这篇关于AuthorizeAttribute使用角色而不是硬编码的角色值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!