繁体   English   中英

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

[英]How to get the name of the role from the Controller to the Custom AuthorizeAttribute class?

我正在开发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]}

但在这里我需要角色的名称。 怎么了

似乎您正在使用属性作为参数。 由于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(){} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM