2012-11-07 35 views
97

我需要根据用户权限级别(没有角色,仅限于分配给用户的CRUD操作级别的权限级别)来控制对视图的访问权限MVC 4应用程序。ASP.NET MVC 4具有权限代码的自定义授权属性(不含角色)

示例如下AuthorizeUser将是我的自定义属性ABD我需要像下面一样使用它。

[AuthorizeUser(AccessLevels="Read Invoice, Update Invoice")] 
public ActionResult UpdateInvoice(int invoiceId) 
{ 
    // some code... 
    return View(); 
} 


[AuthorizeUser(AccessLevels="Create Invoice")] 
public ActionResult CreateNewInvoice() 
{ 
    // some code... 
    return View(); 
} 


[AuthorizeUser(AccessLevels="Delete Invoice")] 
public ActionResult DeleteInvoice(int invoiceId) 
{ 
    // some code... 
    return View(); 
} 

这可能吗?怎么样?在此先感谢...

Chatura

回答

197

我可以用一个自定义属性如下做到这一点。

[AuthorizeUser(AccessLevel = "Create")] 
public ActionResult CreateNewInvoice() 
{ 
    //... 
    return View(); 
} 

自定义属性类,如下所示。

public class AuthorizeUserAttribute : AuthorizeAttribute 
{ 
    // Custom property 
    public string AccessLevel { get; set; } 

    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     var isAuthorized = base.AuthorizeCore(httpContext); 
     if (!isAuthorized) 
     {     
      return false; 
     } 

     string privilegeLevels = string.Join("", GetUserRights(httpContext.User.Identity.Name.ToString())); // Call another method to get rights of the user from DB 

     return privilegeLevels.Contains(this.AccessLevel);   
    } 
} 

您可以通过重写HandleUnauthorizedRequest方法重定向在您的自定义AuthorisationAttribute未经授权的用户:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
{ 
    filterContext.Result = new RedirectToRouteResult(
       new RouteValueDictionary(
        new 
         { 
          controller = "Error", 
          action = "Unauthorised" 
         }) 
       ); 
} 
+0

我想你HandleUnauthorizedRequest的例子,但是当我指定RouteValueDictionary,它只是重定向到我是一条不存在的路线。它附加了我想要重定向用户的路线到用户想要访问的路线... si我得到这样的东西: localhost:9999/admin /首页当我想要 localhost:9999 /首页 – Marin

+1

@Marin尝试在RouteValueDictionary中添加area = string.Empty – Alex

+25

我正在upvoting,但随后在末尾看到“if(condition){return true;} else {return false;}”.... – GabrielBB

1

下面是沪指修改。回答。主要的区别是,当用户没有通过验证,它采用独创的“HandleUnauthorizedRequest”方法来重定向到登录页面:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
    { 

     if (filterContext.HttpContext.User.Identity.IsAuthenticated) { 

      filterContext.Result = new RedirectToRouteResult(
         new RouteValueDictionary(
          new 
          { 
           controller = "Account", 
           action = "Unauthorised" 
          }) 
         ); 
     } 
     else 
     { 
      base.HandleUnauthorizedRequest(filterContext); 
     } 
    }