繁体   English   中英

如何在ASP.Net MVC中实现基于自定义角色的授权

[英]How to implement custom role based authorization in ASP.Net MVC

我正在开发一个项目,我们将Amazon SimpleDB用作数据存储。 在此应用程序中,用户可以在运行时创建角色。 在创建角色时,用户可以为特定功能提供读/写/更新权限。

我试过的代码;

using System;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;


[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class MyAuthorization : ActionFilterAttribute
    {
        public string Model { get; set; }
        public string Action { get; set; }

        public override void OnActionExecuting(HttpActionContext filterContext)
        {
            //My code will go here
            base.OnActionExecuting(filterContext);
        }
    }

在Web API控制器中,我写了;

// GET api/values
        [MyAuthorization(Action = "Edit", Model = "Rack")]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

现在在OnActionExecuting中,我想获取我在APIController中通过action方法指定的Action和Model属性。

如何通过代码处理它,因为在设计时不知道角色名称和权限。

我假设您将在某个控制器中实现的每个功能,每个操作方法指定您正在执行的操作类型(例如,读取,写入等)。

如果我的假设是正确的,您可能必须首先扩展AuthorzeAttribute ASP.NET MVC框架,如下所示。

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class  CustomAuthorizeAttribute : AuthorizeAttribute
{
   public string Operation;

   public override void OnAuthorization(AuthorizationContext filterContext)
   {
      base.OnAuthorization(filterContext);

      //Get the User Id from the session
      // Get Role associated with the user (probably from database)
      // get the permission associated with the role (like Read, write etc)
      // Let assume the retrieved operations are in the form of list of strings
      List<string> retrievedOperations =RetrieveRoleOperations(userId)         

      if (!retrievedOperations.Contains(Operation)
      {
         filterContext.Result = new HttpUnauthorizedResult();
      }
   }

}

创建此类后,您必须在下面所需的操作方法中指定扩展授权过滤器。

Class MyFeatureController:Controller
{
     [MyCustomAuthorize(Operation="Read")]
     public ActionResult MyReadMethod()
     {
        //
     }
}

我希望这能解决你的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM