Search code examples
asp.netasp.net-coreauthorize-attribute

Can I override Authorizations for asp.net core with different Roles?


[Authorize(Roles = "Admin")] // only admin
public class XController : Controller 
{
    [Authorize(Roles = "Employee")] // only employee
    public ActionResult ActionX() { ... }
}

Only admins can access the controller and only employees can access that method, I know that this structure is not the best example but I just would like to know if this is possible! :)


Solution

  • You absolutely can - but for your own sanity (and other developers) I would switch the Employee role to be at the Controller level (least permissive) and then have the more restrictive authorization on your action-by-action basis.

    Straight from the MSDN docs.

    You can further limit access by applying additional role authorization attributes at the action level:

    [Authorize(Roles = "Administrator, PowerUser")]
    public class ControlPanelController : Controller
    {
        public ActionResult SetTime()
        {
        }
    
        [Authorize(Roles = "Administrator")]
        public ActionResult ShutDown()
        {
        }
    }