2012-04-26 83 views
6

我有一個用Jquery的UI,它使用Ajax請求調用MVC。MVC自定義授權屬性來驗證請求

我想驗證每個請求對userProfile(自定義類持有帳號,ID等)。

任何人都可以請建議是否有可能創建自定義的授權屬性來驗證請求和userprofile都是相同的?

然後,我會喜歡這樣做如下:

[AuthorizeUser] 
public ActionResult GetMyConsumption(string accountNumber) 
{ 
    ..... 
    return View(); 
} 
+0

如果你願意將數據分析出來的申請表/查詢字符串並驗證它們,那麼它可能是可能的。您可以在自定義授權屬性中完全訪問httpContext。你必須假設變量「accountNumber」必須存在於表單中,如果是POST,或者QueryString是GET。參數綁定(將請求中的數據映射到Action中的參數)將在授權後的OnActionExecuting方法周圍發生。 – 2012-04-26 04:50:36

+0

Yep accountID將被傳遞。 – 2012-04-26 04:52:04

+1

檢查出http://stackoverflow.com/questions/6860686/extend-authorizeattribute-override-authorizecore-or-onauthorization(AuthorizeCore vs OnAuthorize),這裏有人正在查看某些數據(預算)的某些數據來確定如果用戶是否授權:http://stackoverflow.com/questions/5989100/asp-net-mvc-3-custom-authorisation – 2012-04-26 04:57:04

回答

17

你可以寫一個自定義的授權屬性:

public class AuthorizeUserAttribute : AuthorizeAttribute 
{ 
    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     var isAuthorized = base.AuthorizeCore(httpContext); 
     if (!isAuthorized) 
     { 
      // The user is not authorized => no need to continue 
      return false; 
     } 

     // At this stage we know that the user is authorized => we can fetch 
     // the username 
     string username = httpContext.User.Identity.Name; 

     // Now let's fetch the account number from the request 
     string account = httpContext.Request["accountNumber"]; 

     // All that's left is to verify if the current user is the owner 
     // of the account 
     return IsAccountOwner(username, account); 
    } 

    private bool IsAccountOwner(string username, string account) 
    { 
     // TODO: query the backend to perform the necessary verifications 
     throw new NotImplementedException(); 
    } 
} 
+0

謝謝@Darin Dimitrov – 2012-04-26 10:06:47