0

Is it possible with MVC to allow the whole controller to be accessed by 1 role except one or few methods be accessed by another role?

Where all methods belong to the staff except for Method3 can be access by both clients and staff. Something like below:

    [Authorize(Roles = "staff")]
    public class StaffController : Controller
    {
        public StaffController()
        {
        }
        public ActionResult Method1()
        {
        }
        public ActionResult Method2()
        {
        }
        [Authorize(Roles = "staff, customer")]
        public ActionResult Method3()
        {
        }
    }

Or another scenario where all belong to the staff except for Method3 where it is exclusively accessible by clients, like below:

    [Authorize(Roles = "staff")]
    public class StaffController : Controller
    {
        public StaffController()
        {
        }
        public ActionResult Method1()
        {
        }
        public ActionResult Method2()
        {
        }
        [Authorize(Roles = "customer")]
        public ActionResult Method3()
        {
        }
    }

However, the above don't work. In both cases, clients still don't have access to Method3.

Greatly appreciate any help!

Ramesisiii
  • 207
  • 1
  • 3
  • 10

1 Answers1

0

I suspect it checks for controller authorisation first, so never gets a chance to check the specific actions for their authorisation.

One solution is to authorise both roles, at the class level, and restrict access on specific methods to just staff.

e.g.

[Authorize(Roles="staff,customer")]
public class StaffController : Controller
{
    [Authorize(Roles="staff")]
    public StaffController()
    {
    }
    [Authorize(Roles="staff")]
    public ActionResult Method1()
    {
    }
    [Authorize(Roles="staff")]
    public ActionResult Method2()
    {
    }
    public ActionResult Method3()
    {
    }
}

Another option is to Restrict (i.e. the opposite of Authorize) using something like the custom attribute on this answer ASP.NET MVC: Opposite of [Authorise] but as they mention this goes against the "refuse by default" principal of MVC security.

Community
  • 1
  • 1
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202