簡體   English   中英

如何為角色以及特定用戶使用自定義授權屬性?

[英]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
}

這具有以下優點:

  1. 沒有其他人以后會想知道它在哪里使用的附加類。
  2. 沒有在其他任何地方都無法使用的類(您不會通過自定義屬性獲得重用)
  3. 性能更好:Post 的單次獲取
  4. 人們更容易閱讀/弄清楚它是如何工作的。 沒有神奇的代碼可以追蹤。
  5. 多年后,當 HttpContextBase 類不存在,或者用於獲取 Id 參數的其他部分技巧消失時,代碼仍然有效......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM