2012-04-26 86 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