我有一个使用Jquery的UI,它使用Ajax请求调用MVC。
我想针对userProfile(包含帐号,ID等的自定义类)验证每个请求。
有人可以建议是否可以创建自定义授权属性来验证请求和用户配置文件是否相同?
我想做下面的事情:
[AuthorizeUser]
public ActionResult GetMyConsumption(string accountNumber)
{
.....
return View();
}
答案 0 :(得分: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();
}
}