I have been facing a problem with the [Authorize]
attribute. I have 2 roles Admin and User. I have decorated the controller with the Authorize attribute like [Authorize(Roles = "Admin")]
. But in the same controller I want some methods to be accessible by both Admin and User. What I have studied so far is that the [Authorize]
attribute is additive by default so if I use [Authorize(Roles = "User")]
in the method the user have to be in both Admin and User role to access the method. But the behaviour I want is that the some methods in the controller should be accessible to both roles.
Thanks in advance.
CodePudding user response:
Multiple authorize attributes are additive, but the roles
property is not.
So, this is additive:
[Authorize(Roles = "Admin")]
[Authorize(Roles = "User")]
public class MyController : Controller
{
public IActionResult Index()
{
return Content("You have to be admin AND user to see this");
}
}
And this is additive too:
[Authorize(Roles = "Admin")]
public class MyController : Controller
{
[Authorize(Roles = "User")]
public IActionResult Index()
{
return Content("You have to be admin AND user to see this");
}
}
But this is not:
[Authorize(Roles = "Admin, User")]
public class MyController : Controller
{
public IActionResult Index()
{
return Content("You have to be admin OR user to see this");
}
}
Which means that:
[Authorize(Roles = "Admin, User")]
public class MyController : Controller
{
[Authorize(Roles = "Admin")]
public IActionResult Index()
{
return Content("You have to be admin to see this. But in other methods of this controller you can be Admin OR User");
}
}