Worthy7
Worthy7

Reputation: 1561

Authorization of data in MVC ASP.NET

This is really bugging me but no matter what I read, I cannot seem to understand how to solve this.

I understand that we can assign roles to users. These roles allow certain activities to be done (CRUD operations in controllers).

But how do we restrict what data this applies to? Where can these rules be written down easily so that my controllers don't become super messy?

A super basic example is:

Factory Managers can Update the information about their own Factory, but not those in other Factories. (But they can Read that data)

Of course this can be implemented easily in a NUMBER of ways, but I actually have more a more complex system(FactoryManagers, FactoryWorkers, SupplyManagers, SupplyWorkers), and need a very robust solution. Here are some ideas:

  1. In the repository, write separate querys which restrict the data first. baseRead baseEdit baseUpdate baseDelete. These queries return lists of what can be done for a particular user. They are then combined with the ID specified by the user and will return nothing if it is not in the subset.
  2. Write logic in the controllers to work it out, but this may end up with numerous calls to the database.

Thanks in advance.

Upvotes: 0

Views: 149

Answers (1)

Ahsan
Ahsan

Reputation: 2518

Use a custom Authorization filter, This could only be one approach of many available for this scenario

Following is an summarized code snippet from another answer in SO.

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    // Custom property
    public string AccessLevel { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {                
            return false;
        }

        //do your custom checks here 
        //based on your custom security scenarios and return true or false

    }
}

Usage

[AuthorizeUser(AccessLevel = "Create")]
public ActionResult CreateNewItem()
{
    //...
    return View();
}

See the following for further details

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

http://www.codeproject.com/Articles/577776/Filters-and-Attributes-in-ASPNET-MVC

Upvotes: 1

Related Questions