AuthorizeAttribute with Roles but not hard-coding the Role values

前端 未结 2 1478
礼貌的吻别
礼貌的吻别 2021-01-01 03:40

Is it possible to add the Roles but not hard-coding the values like:

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

I would like to retrieve these r

2条回答
  •  隐瞒了意图╮
    2021-01-01 04:08

    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.

提交回复
热议问题