MVC5 ASP Identity动态授权属性

时间:2015-05-27 03:02:26

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

我有一个带有后端的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

1 个答案:

答案 0 :(得分:3)

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")]