![](/img/trans.png)
[英]How can I use the “Roles” parameter when Customising the Authorize Attribute
[英]How to use custom Authorize attribute for roles as well as a specific user?
我有我的行動方法
[Authorize(Roles="Admin")]
public ActionResult EditPosts(int id)
{
return View();
}
在我的情況下,我需要授權管理員以便他們可以編輯帖子,但是(這里是很酷的部分),我還需要允許帖子的創建者能夠編輯普通用戶的帖子。 那么如何過濾掉創建帖子的用戶和管理員,但讓其他人未經授權呢? 我收到 PostEntry id 作為路由參數,但這是在屬性之后,而且屬性只接受常量參數,看起來非常困難,非常感謝您的回答,干杯!
您可以編寫自定義授權屬性:
public class AuthorizeAdminOrOwnerOfPostAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
if (!authorized)
{
// The user is not authenticated
return false;
}
var user = httpContext.User;
if (user.IsInRole("Admin"))
{
// Administrator => let him in
return true;
}
var rd = httpContext.Request.RequestContext.RouteData;
var id = rd.Values["id"] as string;
if (string.IsNullOrEmpty(id))
{
// No id was specified => we do not allow access
return false;
}
return IsOwnerOfPost(user.Identity.Name, id);
}
private bool IsOwnerOfPost(string username, string postId)
{
// TODO: you know what to do here
throw new NotImplementedException();
}
}
然后用它裝飾你的控制器動作:
[AuthorizeAdminOrOwnerOfPost]
public ActionResult EditPosts(int id)
{
return View();
}
我知道您已經接受了一個答案,並且這是在不久前發布的..(順便說一句:添加自定義屬性的優秀答案),但是我要指出以下幾點:
如果您使用此屬性一次。 在單一方法上。 這不是一個好的實現。 相反,你應該有:
[Authorize] // Just make sure they are auth'ed at all.
public ActionResult EditPosts(int id)
{
Post SomePost = findPostByID (id); // However you do it - single lookup of post
if (!user.IsInRole("Admin") && !{IsOwnerOfPost(post)} ) Return Not Authorized
... Edit post code here
}
這具有以下優點:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.