6

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();
}
tereško
  • 58,060
  • 25
  • 98
  • 150
Nil Pun
  • 17,035
  • 39
  • 172
  • 294
  • If you're willing to parse the data out of the request form/querystring and validate them then it could be possible. You'll have full access to the httpContext in your custom authorize attribute. You would have to assume that a variable "accountNumber" has to exist in the Form if a POST or the QueryString if a GET. Parameter binding (mapping data in the request to parameters in your Action) will happen around the OnActionExecuting method which is post-Authorize. – Nick Bork Apr 26 '12 at 04:50
  • Yep accountID will be passed. – Nil Pun Apr 26 '12 at 04:52
  • 1
    Check out http://stackoverflow.com/questions/6860686/extend-authorizeattribute-override-authorizecore-or-onauthorization (AuthorizeCore vs OnAuthorize) and here is someone who is looking at some Request data (budget) for some data to determine if the user is Authorized or not: http://stackoverflow.com/questions/5989100/asp-net-mvc-3-custom-authorisation – Nick Bork Apr 26 '12 at 04:57

1 Answers1

17

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();
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928