[英]MVC5 ASP Identity dynamic Authorize attribute
我有一個帶后端的MVC5項目來配置哪個角色可以訪問哪個菜單。 實現基於角色的授權的常規方法是這樣的。
[Authorize(Roles="Admin")]
public ActionResult UpdateProduct(ProductModel model)
{
//do something
return View(model);
}
因為我需要角色是動態的,所以我在考慮這樣的事情。
[Authorize(Roles=GetRoles("UpdateProduct"))]
public ActionResult UpdateProduct(ProductModel model)
{
//do something
return View(model);
}
顯然它不起作用,因為屬性是靜態元數據。
我環顧四周,發現這個MVC 3動態授權多個角色和用戶,但有沒有更簡潔的方法來實現這一目標?
注意:我試圖避免在每個方法中調用User.IsInRole
。
C#中代碼屬性的定義是它是靜態的 - 因此你不能擁有一個方法GetRoles()
。
您提議想要一個屬性,例如:
[Authorize(Roles=GetRoles("UpdateProduct"))]
這意味着您必須在代碼中實現GetRoles()
,因此請使用從Authorize
派生的自定義屬性。
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public CustomAuthorizeAttribute(string roleSelector)
{
Roles = GetRoles(roleSelector);
}
private string GetRoles(string roleSelector)
{
// Do something to get the dynamic list of roles instead of returning a hardcoded string
return "Somerole";
}
}
所以現在你可以這樣做:
[CustomAuthorize("updateProduct")]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.