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

时间:2015-08-07 10:39:55

标签: c# asp.net asp.net-mvc asp.net-identity

我正在开发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表中我没有为当前用户分配名称为“Delete COA”的角色。但由于我的CustomeAuthorizeAttribute类没有从控制器获取角色属性的名称,因此我无法根据当前用户的角色进行过滤。

而是构造函数代码

this.allowedroles = roles;

获取字符串:

roles = {string[0]}

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

1 个答案:

答案 0 :(得分: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(){}