【问题标题】:how to use dynamic role in authorize attribute in asp.net mvc 5 identity如何在asp.net mvc 5身份中的授权属性中使用动态角色
【发布时间】:2018-02-15 07:45:31
【问题描述】:

我是 asp.net 身份的新手。我正在努力学习它。我想了解如何在 asp.net MVC 5 身份中的授权属性中使用动态角色。因为如果我们在应用程序中有很多角色,那么我们就不能通过硬编码来装饰它。请详细提供一个很好的例子来帮助我。

提前谢谢你:-)

【问题讨论】:

  • “动态角色”是什么意思?
  • 尝试做一个约定,在 Authorize 属性中使用正则表达式。我以前做过,不知道现在是否支持。

标签: asp.net-mvc asp.net-mvc-4 asp.net-mvc-5 asp.net-identity asp.net-identity-2


【解决方案1】:

扩展 AuthorizeAttribute 以支持像这样的正则表达式:

class RegexAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
        {
           return base.AuthorizeCore(httpContext);
        }

        IPrincipal user = httpContext.User;
        if (user == null || user.Identity == null || !user.Identity.IsAuthenticated)
        {
            return base.AuthorizeCore(httpContext);
        }

        if (!string.IsNullOrEmpty(Users) && Regex.IsMatch(user.Identity.Name, Users))
        {
            return true;
        }

        if (!string.IsNullOrEmpty(Roles))
        {
            var rolesManager = new RoleStore<IdentityRole>(httpContext.GetOwinContext().Get<ApplicationDbContext>());
            var matchedRoles = rolesManager.Roles.Select(t => t.Name).AsEnumerable().Where(t => Regex.IsMatch(t, Roles));

            if (matchedRoles.Any(user.IsInRole))
            {
                return true;
            }
        }

        return base.AuthorizeCore(httpContext);
    }
}

稍后你可以将你的角色组织成组,以便能够使用如下正则表达式匹配一堆角色:

    [RegexAuthorize(Roles = @"Role #\d")]
    public ActionResult About()
    {
        ViewBag.Message = "Your application description page.";

        return View();
    }

这将匹配以下所有角色:角色 #0、角色 #1、...、角色 #9

希望对您有所帮助!

【讨论】:

    【解决方案2】:

    您可以在此链接中找到 microsoft 支持的完整解释和演示项目,其中包含有关使用 mvc 身份和角色、声明 ....的多个示例。

    MVC_Identity

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-25
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      • 2016-01-09
      • 2013-12-21
      • 2014-07-19
      • 2015-11-19
      相关资源
      最近更新 更多