5.12. Authorizing Access to Controller Methods

Now we can limit (filter) access to the methods of various controllers using the Authorize attribute. We have already seen how it is used in the AccountController controller:

  1. [Authorize(Roles = "admin")]
  2. public ActionResult Register()
  3. {…

This filter can be used at two levels: on a controller as a whole and on an individual operation of a controller. We will set different rights for our main controllers: CustomerController, InvoiceController and ProductController. In our project, a user with the MANAGER role can view and edit data in all three tables. Setting a filter for the InvoiceController controller would be coded as follows:

  1. [Authorize(Roles = "manager")]
  2. public class InvoiceController : Controller
  3. {
  4. private DbModel db = new DbModel();
  5. // Show view
  6. public ActionResult Index()
  7. {
  8. return View();
  9. }

Setting filters in the other controllers can be implemented in a similar manner.