【问题标题】:How to get the name of the role from the Controller to the Custom AuthorizeAttribute class?如何从 Controller 中获取角色的名称到自定义 AuthorizeAttribute 类?
【发布时间】:2015-10-30 18:44:16
【问题描述】:

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

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

【问题讨论】:

  • 你在寻找this.allowedroles = Roles; 为什么要检索特定角色的所有用户,以授权一个用户,这没有意义
  • 假设我有一个用户有 3 个不同的角色,而另一个用户只有一个角色。因此,当第二个用户尝试访问其他 2 个角色(未分配给他)时,应该拒绝他访问。如果我不能从控制器获得角色的名称,我怎么能拒绝或允许它。我该怎么办??
  • 我是 asp.net 身份的新手,所以请指导我实施它。@3dd
  • bcoz 该方法只检查当前用户是否具有任何给定的角色。它不检查哪个角色被赋予了用户,哪个不是
  • 如果属性中有多个角色,它们通常用,分隔符指定,因此您可以使用var roles = Rols.split(','),然后在数组上使用contains来查找用户是否可以访问资源

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-01-01
    • 2020-03-07
    • 2021-07-19
    • 2019-07-11
    • 2021-01-09
    • 2013-11-04
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    相关资源
    最近更新 更多