MVC Custom Authorize Attribute to validate the Request
asp.net-mvc, asp.net-mvc-3
Solution
You could write a custom Authorize attribute:
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();
}
}
Problem
I've a UI with Jquery which makes a call to MVC using Ajax request. I would like to validate each request against the userProfile (custom class which holds account number, ID etc). Could anyone please suggest whether it is possible to create custom Authorize Attribute to validate that both request and userprofile are same? I would then like to do something like below: ``` [AuthorizeUser] public ActionResult GetMyConsumption(string accountNumber) { ..... return View(); } ```