Make a role that is always allowed, even if it is not listed

In MVC3, is there a way to make a role (SuperAdmin) that is ALWAYS authorized, even if it is not explicitly listed in the Roles list?

For example, with this markup ...

[Authorize(Roles="Accounting")]

Even if I am not in the role of Accounting, since SuperAdmin is there an authorization method for this action?

+4
source share
2 answers

You can create your own custom AuthorizeAttribute , where in the AuthorizeCore method you can implement additional logic.

A simple example without proper error handling:

 public class AuthorizeSuperAdminAttribute : AuthorizeAttribute { protected virtual bool AuthorizeCore(HttpContextBase httpContext) { IPrincipal user = httpContext.User; if (user.Identity.IsAuthenticated && user.IsInRole("SuperAdmin")) return true; return base.AuthorizeCore(httpContext); } } 

Then you can use it usually in your actions:

 [AuthorizeSuperAdmin(Roles="Accounting")] public ActionResult MyAction() { } 
+1
source

I highly recommend reading Protect ASP.NET MVC 3 Application .

First create your AnonymousAttribute :

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public sealed class AllowAnonymousAttribute : Attribute { } 

Second, create your GlobalAuthorize attribute:

 public sealed class GlobalAuthorize : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { bool bypassAuthorization = filterContext.ActionDescriptor .IsDefined(typeof(AllowAnonymousAttribute), true) || filterContext.ActionDescriptor .ControllerDescriptor .IsDefined(typeof(AllowAnonymousAttribute), true) || (filterContext.RequestContext .HttpContext .User != null && filterContext.RequestContext .HttpContext .User .IsInRole("SuperAdmin")); if (!bypassAuthorization) { base.OnAuthorization(filterContext); } } } 

Third, register GlobalAuthorize in global filters (global.asax):

 public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new GlobalAuthorize()); } 

Now all controllers require user login to access. Controllers OR controllers Methods may be allowed Anonymous access with the AllowAnonymous attribute. In addition, all users are allowed in the SuperAdmin role.

+2
source

All Articles