2016-08-12 31 views
0

在我的控制器中,我有一些代碼,如[Authorize(Roles = "Administrators")]註釋了某些操作,並且我想知道AuthorizeAttribute如何使用Roles參數(檢查機制的實現)。我的目標是創建此類的擴展名,例如PrivilegeAttribute,以便我可以註釋[Privilege(Privileges = "read")]之類的操作。在這個類中,我將檢查用戶角色是否至少具有此自定義過濾器中的一個權限(本例中爲read)。我已經在代碼和數據庫中創建了角色和特權之間的關聯,我想要幫助的是檢查角色是否與特權相關聯。ASP.NET MVC AuthorizeAttribute如何支持檢查角色?

我試着去看看這個信息是否在HttpContextBase.User.Identity裏面,但是我找不到它。 謝謝。

+1

看看這個問題:http://stackoverflow.com/questions/5117782/how-to-extend-authorizeattribute - 和 - 檢查 - 的 - 用戶 - 角色。我也發現這個指南:http://www.diaryofaninja.com/blog/2011/07/24/writing-your-own-custom-aspnet-mvc-authorize-attributes –

回答

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的源代碼應該是一個好的起點