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:
[Authorize(Roles = "admin")]
public ActionResult Register()
{…
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:
[Authorize(Roles = "manager")]
public class InvoiceController : Controller
{
private DbModel db = new DbModel();
// Show view
public ActionResult Index()
{
return View();
}
…
Setting filters in the other controllers can be implemented in a similar manner.