2014-05-02 24 views
1

我正在使用Amazon SimpleDB作为数据存储的项目。在这个应用程序中,用户可以在运行时创建角色。在创建角色时,用户可以为特定功能提供读/写/更新权限。如何在ASP.Net中实现基于自定义角色的授权MVC

我试过的代码;

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方法中指定。

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

回答

3

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

如果我的假设是正确的,那么您可能必须首先像下面那样扩展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() 
    { 
     // 
    } 
} 

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

+0

你能帮我一下,如何用WebAPI做到这一点? –

+0

您已经在“MyAuthorization”过滤器上指定了一些常量值,并且可以通过使用this.Action和this.Model在类中访问相同的值。但看起来你正在寻找更多的东西。不知道你到底在找什么。你想访问在控制器中实例化的模型吗? – Sankaran