Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Custom Authorize Attribute to validate the Request

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();
}
like image 416
Nil Pun Avatar asked Apr 26 '12 04:04

Nil Pun


People also ask

What does Authorize attribute do in MVC?

In MVC, the 'Authorize' attribute handles both authentication and authorization. In general, it works well, with the help of extension to handle AJAX calls elegantly, and to distinguish between unauthorized users and those who are not logged in.

How do I set an authorized role in MVC?

Open Visual Studio 2015 or an editor of your choice and create a new project. Choose "web application" project and give an appropriate name to your project. Select "empty" template, check on the MVC box, and click OK. Right-click on the Models folder and add a database model.

How do I Authorize in MVC 5?

Usage. Then you can start using [Authorize] attribute in Controller and Action methods. [Authorize(Roles = "Power Users")] public class UsersController : Controller { // ... }


1 Answers

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();
    }
}
like image 96
Darin Dimitrov Avatar answered Nov 09 '22 00:11

Darin Dimitrov