我有一个使用Jquery的UI,它通过Ajax请求调用MVC。
我想根据用户资料(自定义类,包含帐号、ID等)验证每个请求。
请问是否可能创建自定义授权属性来验证请求和用户资料是否相同?
然后,我想做以下操作:
[AuthorizeUser]
public ActionResult GetMyConsumption(string accountNumber)
{
.....
return View();
}
我有一个使用Jquery的UI,它通过Ajax请求调用MVC。
我想根据用户资料(自定义类,包含帐号、ID等)验证每个请求。
请问是否可能创建自定义授权属性来验证请求和用户资料是否相同?
然后,我想做以下操作:
[AuthorizeUser]
public ActionResult GetMyConsumption(string accountNumber)
{
.....
return View();
}
你可以编写一个自定义的授权属性:
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();
}
}