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.
source share