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

标签 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!"); }
    }

现在我的 Controller 授权如下:

[CustomAuthorize(Roles="Delete COA")]

即使在 dbo.AspNetRoles 表中我没有为名称为“Delete COA”的当前用户分配任何角色,我的代码也会为它授权当前用户。但是由于我的 CustomeAuthorizeAttribute 类没有从 Controller 获取角色属性的名称,我无法根据当前用户的角色进行过滤。

代替构造函数代码

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(){} 

关于c# - 如何从 Controller 获取角色名称到 Custom AuthorizeAttribute 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31875735/

相关文章:

c# - 随机枚举生成

c# - XmlSerializer 和 xsi :type

c# - 是否可以在 Asp.NET razor 代码中嵌套 foreach 循环?

asp.net-mvc - 客户 ActionFilterAttribute 的单元测试失败

javascript - 从 angularjs 中的 OAuth2 授权端点检索 token

html - 将 anchor 标记的显示分成多行

c# - 在 Excel 之外运行 XLL?

c# - 通用委托(delegate)线程

c# - asp.net 从代码隐藏页面插入 HTML

c# Asp.net 文本框的验证方法?