ASP.NET MVC AuthorizeAttribute如何支持检查角色?

时间:2016-08-12 17:31:59

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

在我的控制器中,我的代码如[Authorize(Roles = "Administrators")]注释了一些操作,我想知道AuthorizeAttribute如何使用Roles参数(检查机制的实现)。我的目标是创建一个名为PrivilegeAttribute的类的扩展,以便我可以注释[Privilege(Privileges = "read")]之类的操作。在本课程中,我将检查用户的角色是否至少具有此自定义过滤器中的一个权限(在此示例中为read)。我已经在代码和数据库中创建了角色和权限之间的关联,我想要帮助的是检查角色是否与权限相关联。

我试着查看HttpContextBase.User.Identity中是否存在该信息,但我无法找到它。 谢谢。

1 个答案:

答案 0 :(得分:1)

如果您不需要自己的自定义属性并且可以使用其他人属性,那么我建议使用此处所述的Thinktecture.IdentityModel.Owin.ResourceAuthorization.Mvc包

Blog Post by Dominick Baier

在这里

Git Hub Sample Code for the Package

所以它基本上是这样的: 你把一个属性放在你的行动上:

[ResourceAuthorize("View", "Customer")]

第一个参数是要检查的Action的名称,第二个参数是属性的名称。

然后从代码中的ResourceAuthorizationManager派生并覆盖CheckAccessAssync方法

public class MyAuthorization : ResourceAuthorizationManager
{
    public override Task<bool> CheckAccessAsync(ResourceAuthorizationContext context)
    {
        var resource = context.Resource.First().Value;
        var action =  context.Action.First().Value;

        // getting the roles that are connected to that resource and action
        // from the db. Context could of course be injected into the 
        // constructor of the class. In my code I assume that the table
        // thank links roles, resources and actions is called Roles ToActions
        using(var db = MyContext())
        var roles = db.RolesToActions   // Use your table name here
         .Where(r => r.Resource == resource && r.Action == action).ToList();

        foreach(var role in roles)
        {
            if(context.Principal.IsInRole(role.Name)
            {
                return Ok();
            }
        }

        return Nok();
    }
 }

}

所以我希望这会有所帮助。但是,如果您希望实现自己的属性,那么ResourceAuthorization GitHub Repository中的源代码应该是一个很好的起点