ASP.NET MVC: can I say [Authorize Roles = "Administrators"] in the Controller class, but is there one public action?

I started using the default project AccountController , but I expanded it / changed it beyond recognition. However, as in the original, I have a LogOn and LogOff .

Obviously, the LogOn action should be available to everyone. However, since I added many other actions to this controller (for creating and editing users), I want 99% of the actions to require membership in the administrator role.

I could decorate all my actions [Authorize Roles="Administrators"] , but there is a risk that I will forget it. I would prefer to make it safe by default by decorating the controller class itself with this attribute, and then canceling the requirement in my LogOn method. Can I do it?

(As in, can I do this out of the box without creating custom classes, etc. I donโ€™t want to complicate things more than necessary.)

+5
authorization asp.net-mvc
Mar 29 '10 at 10:52
source share
3 answers

To override the controller attribute at the action level, you need to create a custom attribute, and then set the Order property of your custom attribute to a higher value than the AuthorizeAttribute controller. I believe that both attributes are then executed if your custom attribute does not produce a result with immediate effect, such as a redirect.

See Overriding an AuthorizeAttribute controller in just one step for more information.

So, I believe in your case, you just need to add AuthorizeAttribute to actions, not at the controller level. However, you could create a unit test to ensure that all actions (except LogOn) have an AuthorizeAttribute attribute

+4
Mar 29 '10 at 12:55
source share

You can use AuthorizeAttribute in your class

http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.aspx

For relaxation, you can implement, for example, an attribute of a custom action filter similar to this (I have not tested whether it works).

 public class GetRidOfAutorizationAttribute : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { // you can for example do nothing filterContext.Result = new EmptyResult(); } } 
+2
Mar 29 '10 at 11:13
source share

After too much time, I came up with a solution.

 public class OverridableAuthorize : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { var action = filterContext.ActionDescriptor; if(action.IsDefined(typeof(IgnoreAuthorization), true)) return; var controller = action.ControllerDescriptor; if(controller.IsDefined(typeof(IgnoreAuthorization), true)) return; base.OnAuthorization(filterContext); } } 

which can be paired with IgnoreAuthorization in action

 public class IgnoreAuthorization : Attribute { } 
+2
Mar 04 '13 at 23:13
source share



All Articles