Securing controller action methods using filters
You might want to ensure that one particular action method of a controller class can only be called by members of certain security roles. You do this by decorating the method with the [Authorize]
attribute, as described in the following list:
[Authorize]
: Only allow authenticated (non-anonymous, logged-in) visitors to access this action method.[Authorize(Roles = "Sales,Marketing")]
: Only allow visitors who are members of the specified role(s) to access this action method.
Let's see an example:
- In
HomeController.cs
, import the namespace for working with authorization, as shown in the following code:
using Microsoft.AspNetCore.Authorization; // To use [Authorize].
- Add an attribute to the
ModelBinding
method to only allow access to logged-in users who are members of a group/role namedAdministrators
, as shown highlighted in the following code:
[Authorize(Roles = "Administrators")]
public IActionResult ModelBinding...