I currently have a few controllers which I've restricted with the [Authorize]
decorator. I now need to do this in a few different controllers, is there a central location which this can be put in? Once in that location I can tell it which Controllers to apply that to, rather than me putting it to each individual controller file?
Asked
Active
Viewed 76 times
1

Paritosh
- 4,243
- 7
- 47
- 80
-
you can create a custom filter, but that would apply it globally – blogbydev Oct 13 '15 at 15:01
-
1you can create baseController that has authorize attribute.Because attributes are inherited too.Even you can create hierarchy according to role authorization.See answer for more information http://stackoverflow.com/a/32803405/4293929 – Mustafa ASAN Oct 13 '15 at 16:19
2 Answers
2
How about something like this:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
string controllerName = actionContext.ControllerContext.ControllerDescriptor.ControllerName;
bool shouldAuthorize = //.. Check if controller needs authorization
if(!shouldAuthorize)
SkipAuthorization(actionContext);
else if(!IsAuthorized(actionContext))
HandleUnauthorizedRequest(actionContext);
}
}
Then you would apply this filter globally:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new CustomAuthorizeAttribute());
}
Note that the controller verification is done inside the custom attribute.

Matias Cicero
- 25,439
- 13
- 82
- 154
0
You can make a base controller your other controllers inherit from. In this class apply your main authorization attribute.
Namespace Controllers
<SecureAuthorizeAttribute>
Public Class SecureController
Inherits Controller
End Class
End Namespace
Then in your other controllers:
Public Class ViewDetailsController
Inherits SecureController
End Class
This will apply <SecureAuthorizeAttribute>
to every action in classes that inherit from SecureController
.

rogerdeuce
- 1,471
- 6
- 31
- 48