I have sets of controllers which are each used for each authorization type. For example, a class A authorization will have a set of controllers each which require class A authorization. Is there a way to place one [Authorize(Role="Class A")]
attribute somewhere which will apply to each of those controllers without having to decorate each controller with the same attribute?
You can initialize those controllers derived from your base controller. namely put your attribute on a controller base class and to ensure that each controller within derived from base class.
[Authorize(Role="Class A")]
public class CustomBaseController : Controller{}
public class AController: CustomBaseController{}
public class BController: CustomBaseController{}
Yes there is a way, make all those A-class
controller derived from one base controller and place on it the AuthorizeAttribute
:
[Authorize(Role="Class A")]
public class AController : Controller
{
...
}
public class AFirstController : AController // Gets it's parent attribute
{
...
}
public class ASecondController : AController // Gets it's parent attribute
{
...
}
2 or 3 responses here explained how you can do it... but you can also use Fluent Security to handle all controllers + Actions setup in one file. Some of the benefits (from their website):
Code based configuration
No attributes or xml cluttering up your code.
Low imprint
Fluent Security won't spread like wildfire in your application. Your configuration can be kept in a single file.
You can inherit from a base controller, such as
[Authorize(Role = "Class A")]
public class ClassARequiredController : Controller {}
Otherwise you'd be looking at a global filter, and by your question I assume you have multiple roles and sets so I don't think global filters are for you.
Set the attribute on a Base Class and inherit, creating the hierarchy that best fits your scenario...
来源:https://stackoverflow.com/questions/9830906/how-to-authorize-a-set-of-controllers-without-placing-the-annotation-on-each-one