How to authorize a set of controllers without placing the annotation on each one?
Asked Answered
C

5

8

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?

Cogitable answered 22/3, 2012 at 21:34 Comment(0)
V
11

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{}
Viminal answered 22/3, 2012 at 21:41 Comment(2)
Plus, depending upon the number of controllers you have, you could just as easily place that pesky [Authorize] attribute at the top. With having a base controller it seems you are going to have to mess with each controller anyways.Stricklin
Yes, but using base controller is a best practice for initilazing and checking some datas for all controller. Maybe you want to use custom Authorize attribute. Also made changes on Custom Authorize attribute on a single controller is easy.Viminal
I
4

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
{
    ...
} 
Israelisraeli answered 22/3, 2012 at 21:38 Comment(0)
I
4

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.

Ioves answered 22/3, 2012 at 22:27 Comment(1)
URL now defaults to a domain parking page. Is Fluent Security still a thing?Careworn
V
3

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.

Verdi answered 22/3, 2012 at 21:38 Comment(0)
P
2

Set the attribute on a Base Class and inherit, creating the hierarchy that best fits your scenario...

Placenta answered 22/3, 2012 at 21:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.