Use the Authorize attribute without parameters for the controller:
[Authorize] public class MyController : Controller { ... public AllUsersAction() { } [Authorize(Users="Admin")] public ActionResult OnlyForAdmin() { } }
And specify Authorize attribute properties for roles / users for limited actions.
Unfortunately, the Authorize attribute on the controller bypasses authorization only if the action has the AllowAnonymous attribute. Fortunately, you can override the OnAuthorization method of the Authorize attribute to skip the authorization check in the controller. Authorize an attribute if the action has its own Authorize attribute:
public class CustomAuthorize : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { if(filterContext.ActionDescriptor.IsDefined(typeof(AuthorizeAttribute), true)) {
You can use this CustomAuthorize in your example:
[CustomAuthorize(Users="Admin")] public class MyController : Controller { ... [Authorize] public AllUsersAction() { } }
source share