如果你不需要自己的自定義屬性,並可以使用別人的屬性,比我會建議使用包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的源代碼應該是一個好的起點
看看這個問題: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 –