加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-3 – 具有角色的AuthorizeAttribute但不对角色值进

发布时间:2020-12-16 07:32:06 所属栏目:asp.Net 来源:网络整理
导读:是否可以添加角色,但不能对以下值进行硬编码: [Authorize(Roles="members,admin")] 我想从数据库或配置文件中检索这些角色,如果我需要为Controller Action添加/删除角色,我将不需要重建应用程序. 我知道可以用枚举来做… http://www.vivienchevallier.com/A
是否可以添加角色,但不能对以下值进行硬编码:

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

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

我知道可以用枚举来做…
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));
    }
}

我希望它对你有所帮助.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读