簡體   English   中英

ASP.NET MVC-授權重構

[英]ASP.NET MVC - Authorization Refactor

我在這段代碼中看到的問題是,它將被大量重用。 經過身份驗證的用戶(網站管理員除外)正在編輯/創建的任何內容都只能訪問其“工作室”對象。

我對大家的問題; 您將如何重構它,以便可以從客戶的知識中抽象出服務層。 我打算稍后在獨立的桌面應用程序中重用服務層。

請闡明我的錯誤方法! 我非常感謝。

AuthorizeOwnerAttribute.cs (AuthorizeAttribute)

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    // Get the authentication cookie
    string cookieName = FormsAuthentication.FormsCookieName;
    HttpCookie authCookie = httpContext.Request.Cookies[cookieName];

    // If the cookie can't be found, don't issue the ticket
    if (authCookie == null) return false;

    // Get the authentication ticket and rebuild the principal & identity
    FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    string[] userData = authTicket.UserData.Split(new[] { '|' });

    int userId = Int32.Parse(userData[0]);
    int studioID = Int32.Parse(userData[1]);
    GenericIdentity userIdentity = new GenericIdentity(authTicket.Name);
    WebPrincipal userPrincipal = new WebPrincipal(userIdentity, userId, studioID);
    httpContext.User = userPrincipal;

    return true;
}

在我的“用戶”控制器內部,將此屬性附加到需要所有者的任何方法上

    [AuthorizeOwner]
    public ActionResult Edit(int Id)
    {
        IUser user = userService.GetById(HttpContext.User, Id);
        return View(user);
    }

現在,在我的服務層中,我正在檢查傳遞的IPrincipal是否有權訪問所請求的對象。 這是它越來越臭的地方:

UserService.cs

    public IUser GetById(IPrincipal authUser, int id)
    {
        if (authUser == null) throw new ArgumentException("user");

        WebPrincipal webPrincipal = authUser as WebPrincipal;
        if (webPrincipal == null) throw new AuthenticationException("User is not logged in");

        IUser user = repository.GetByID(id).FirstOrDefault();
        if (user != null)
        {
            if (user.StudioID != webPrincipal.StudioID) throw new AuthenticationException("User does not have ownership of this object");
            return user;
        }

        throw new ArgumentException("Couldn't find a user by the id specified", "id");
    }

我不確定我是否會將實際ID存儲在cookie中,這有點暴露了。 我更傾向於使用Session哈希存儲該數據,從而將其保留在服務器上而不公開。

我還將使用模型(通過傳遞用戶ID)來確定要返回的對象,即具有匹配studioID的對象。 這樣,您的控制器將只需要調用“ GetObjects(int id)”,如果它們無權訪問任何內容,那么您將獲得一個null或空集合。 這對我來說比較干凈。

暫無
暫無

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

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