首页 文章

如何从 Controller 获取角色的名称到 Custom AuthorizeAttribute 类?

提问于
浏览
1

我正在开发 MVC 应用程序并使用 ASP.NET 身份用于用户角色。我将 AuthorizeAttribute 类的 3 个函数覆盖为:

public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        private ApplicationDbContext context = new ApplicationDbContext();
        private readonly string[] allowedroles;        
        public CustomAuthorizeAttribute(params string[] roles)
        { this.allowedroles = roles; }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            string usr = httpContext.User.Identity.Name;
            var userId = context.Users.Where(item => item.UserName == usr).Single().Id;
            var uroles = context.Roles.ToList();
            bool authorize = false;
            foreach (var role in uroles)
            {
                var user = context.Users.Where(u => u.Roles.Any(r => r.RoleId == role.Id)).ToList();
                if (user.Count() > 0)
                { authorize = true; }
            }
            return authorize;
        }
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        { filterContext.Result = new HttpUnauthorizedResult("Access is Denied!"); }
    }

现在我的控制器授权如下:

[CustomAuthorize(Roles="Delete COA")]

我的代码为当前用户授权,即使在 dbo.AspNetRoles 表中我没有为当前用户分配名称为“删除 COA”的角色。但由于我的 CustomeAuthorizeAttribute 类没有从控制器获取角色属性的名称,因此我无法根据当前用户的角色进行过滤。

而是构造函数代码

this.allowedroles = roles;

获取字符串:

roles = {string[0]}

但我需要这个角色的名字。这有什么不对?

1 回答

  • 3

    您似乎使用属性作为参数。由于AuthorizeAttribute已经有Role属性,你可以简单地使用它。

    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        private ApplicationDbContext context = new ApplicationDbContext(); 
    
        // you don't need the constrictor and private roles field  
    
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            // spiting different roles by ',' 
            var roles=this.Rols.Split(',');
            // rest of your code
        }
    }
    

    你可以申请任何行动:

    [CustomAuthorize(Roles="Delete COA")]
    public ActionResoult MyFancyAction(){}
    

    或者对于多个角色,您可以:

    [CustomAuthorize(Roles="FirstRole,SecondRole,AndSoOn")]
    public ActionResoult MyFancyAction(){}
    

相关问题