Asp.net mvc 每个域实体的用户角色关联

Asp.net mvc 每个域实体的用户角色关联,asp.net-mvc,authorization,Asp.net Mvc,Authorization,我的数据库中有以下结构: 因此,我想使用MVC的内置授权属性来过滤控制器中由不同成员执行的操作 如果user1对entity1或其下的任何实体执行删除操作,我会说什么?我可以查看他是否具有执行该操作的正确角色,并相应地过滤该操作 解决这一问题的最佳做法是什么? 我应该创建自己的权限引擎来提供我需要的答案,还是可以使用现有的功能 解决这一问题的最佳做法是什么 自定义[Authorize]似乎是实现此逻辑的好地方 public class MyAuthorizeAttribute : Authori

我的数据库中有以下结构:

因此,我想使用MVC的内置授权属性来过滤控制器中由不同成员执行的操作

如果user1对entity1或其下的任何实体执行删除操作,我会说什么?我可以查看他是否具有执行该操作的正确角色,并相应地过滤该操作

解决这一问题的最佳做法是什么? 我应该创建自己的权限引擎来提供我需要的答案,还是可以使用现有的功能

解决这一问题的最佳做法是什么

自定义
[Authorize]
似乎是实现此逻辑的好地方

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authorized = base.AuthorizeCore(httpContext);
        if (!authorized)
        {
            // the use ris not authenticated or not authorized - no need to continue
            return false;
        }

        string username = httpContext.User.Identity.Name;
        // read the entity id that this user is attempting to manipulate
        string entityId = (string)httpContext.Request.RequestContext.RouteData.Values["id"] ?? httpContext.Request["id"];

        return IsAllowed(username, entityId);
    }

    private bool IsAllowed(string username, string entityId)
    {
        // You know what to do here - hit the database and check whether
        // the current user is the owner of the entity
        throw new NotImplementedException();
    }
}
然后:

[HttpDelete]
[MyAuthorize]
public ActionResult Delete(int id)
{
    ...
}

非常感谢。这实际上很有帮助。。我从未创建过自己的自定义属性,这将是一个很好的练习场所:)。。您还写了一个问题,但在当前上下文中,我如何找出用户试图操纵的实体?。。我应该从查询字符串中读取它吗..是的,它下面的行就是这样做的-它从RoutedData或请求中读取实体id。您的控制器操作必须以某种方式传递此信息。我没有想到我可以在重写属性时访问路由数据。。。谢谢,效果很好!:)
[HttpDelete]
[MyAuthorize]
public ActionResult Delete(int id)
{
    ...
}