2015-10-11 27 views
3

我需要根據用戶ID來控制對我的控制器編輯方法的訪問權限,即只有該用戶可以訪問創建該特定數據的編輯方法。 用戶標識存儲在表EmpProfile UserID列中,並希望將當前登錄用戶與存儲的用戶標識進行比較,並允許在此基礎上進行訪問。 我的自定義授權屬性代碼爲:如何通過比較存儲在表中的用戶標識和Asp.net MVC 5中的當前用戶標識來創建自定義授權屬性?

public class AuthorizeAuthorAttribute : AuthorizeAttribute 
{   
    RecruitDB mydb = new RecruitDB(); // My Entity 
    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     var isAuthorized = base.AuthorizeCore(httpContext); 
     if (!isAuthorized) 
     { 
      return false; 
     } 
     string CurrentUser = httpContext.User.Identity.GetUserId().ToString(); // Current User ID(Converted to string) 

     var userName = from m in mydb.EmpProfiles   //Calling method to get UserID from EmpProfile.UserID Column 
         where m.UserID == CurrentUser 
         select m.UserID; 
     string my = userName.ToString();     //Converting to string 
     if (CurrentUser.Contains(my))      //Comparing 
     { 
      return true; 
     } 
     else 
     { 
      return false; 
     } 
    } 
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
    { 
     filterContext.Result = new HttpUnauthorizedResult(); 
    }  
} 

控制器代碼:

[AuthorizeAuthor] 
    public ActionResult Edit(int? id) 
    { 
    } 

但通過將授權我總是定向到登錄頁面。 同樣當用戶與作者相同時。

+1

我不認爲在屬性邏輯應該是「重」(例如通過執行數據庫命中)。最初的授權屬性僅比較用戶的auth cookie中的數據,這是快速的內存中邏輯。通過在屬性中隱藏昂貴的代碼,您可以將應用程序邏輯的複雜性隱藏給其他開發人員。 – Dai

+0

通過向我的操作添加[Authorize(User =「SomeUser」)],只允許特定的硬編碼用戶輸入。但是用戶如何創建數據只能得到授權。因爲它當前的用戶ID和數據創建者用戶ID應該匹配。很像站點用戶儀表板只能由用戶創建它訪問。 MVC是否提供這種授權?請指教。 – Fahad

回答

1

在回答您的評論:

通過增加[Authorize(User="SomeUser")]到我的行動只允許特定的硬編碼的用戶輸入。但是用戶如何創建數據只能得到授權。因爲它當前的用戶ID和數據創建者用戶ID應該匹配。很像站點用戶儀表板只能由用戶創建它訪問。 MVC是否提供這種授權?請建議

注意到Authorize屬性與.NET中的所有屬性一樣,只能有const參數,這是正確的。

爲了提高靈活性,你不能在這種情況下使用屬性,你必須實現自己的授權邏輯,並從你的控制器動作進行調用,就像這樣:

public ActionResult Edit(Int32? id) { 
    // Repeat the below logic for each action you want access-control in, ensure it is also in your POST handlers too. 
    if(!this.IsAuthorized()) return this.Http401(); 
} 

protected boolean IsAuthorized() { 
    if(this.Request.User.Identity.Name == "someoneIDontLike") return false; 
    return true; 
} 

protected ActionResult Http401(String message) { 
    this.Response.StatusCode = 401; 
    // This requires you to create your own custom HTTP 401 "Unauthorized" view file and viewmodel 
    return this.View(new Http401ViewModel(message)); 
} 
+0

我在EmpProfile表中存儲了用戶標識並將其作爲userName進行檢索,並將其與User.Identity.GetUserId()進行比較,並將其傳遞給if(IsAuthorized(id))語句。編輯邏輯位於If語句內部但不工作... – Fahad

相關問題