【问题标题】:MVC5 ASP Identity dynamic Authorize attributeMVC5 ASP 身份动态授权属性
【发布时间】:2015-05-27 03:02:25
【问题描述】:

我有一个带有后端的 MVC5 项目来配置哪个角色可以访问哪个菜单。实现基于角色的授权的正常方式是这样的。

[Authorize(Roles="Admin")]
public ActionResult UpdateProduct(ProductModel model)
{
     //do something
     return View(model);
}

因为我需要角色是动态的,所以我正在考虑这样的事情。

[Authorize(Roles=GetRoles("UpdateProduct"))]
public ActionResult UpdateProduct(ProductModel model)
{
     //do something
     return View(model);
}

显然它不起作用,因为属性是静态元数据。

我环顾四周,发现了这个MVC 3 dynamic authorization of multiple roles and users,但有没有更简洁的方法来实现这一点?

注意:我试图避免在每个方法中调用User.IsInRole

【问题讨论】:

    标签: c# asp.net-mvc authorization asp.net-identity authorize-attribute


    【解决方案1】:

    C# 中代码属性的定义是它是静态的 - 因此你不能有一个方法,GetRoles()

    您建议想要一个属性,例如:

    [Authorize(Roles=GetRoles("UpdateProduct"))]

    这意味着您必须在代码中实现GetRoles(),因此请使用派生自Authorize 的自定义属性。

        public class CustomAuthorizeAttribute : AuthorizeAttribute
        {
    
            public CustomAuthorizeAttribute(string roleSelector)
            {
    
                Roles = GetRoles(roleSelector);
            }
    
            private string GetRoles(string roleSelector)
            {
                // Do something to get the dynamic list of roles instead of returning a hardcoded string
                return "Somerole";
            }
    }
    

    所以现在你可以这样做了:

    [CustomAuthorize("updateProduct")]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-22
      • 2010-11-01
      • 2016-04-24
      • 2014-05-31
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多