Authorization Filter – Reusable/Common components for ASP.NET MVC 3.0
July 20, 2011 Leave a Comment
Suppose we want to apply an authorization to every action except the action that lets the user login than Decorate [Authorize] attribute to all methods except login one.
There are some risks if we follow above approach.
1. Programmer might miss to decorate one or more method (Security risk)
2. Maintainability issue. Require to prepare tracker.
To solve above problem, now ASP.NET MVC 3 introduces global filters. For this we have to create class which derived from Authorize class (LogonAuthorize – which I have created ) and register into Global.asax.
Once we register custom Authorize class into Global.asax, it introduce another problem. We can’t call the logon and registration methods too because we have set globally that before calling any action method, user must be login into application.
To solve above problem, we have to write attribute (AllowAnonymous – which I have created) and inform to the application that don’t expect login if any action method is decorated with AllowAnonymous.
I have made class library for LogonAuthorize and AllowAnonymous. So any consumer should give the reference of dll and add below code in respected global.asax (In pinkcolour).
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new LogonAuthorize());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
Now for action method, decorate AllowAnonymous , if we want to give Anonymous access.
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
So now when we run the application, we can call Register action before login.
Even after implementing custom filter, we can decorate action method with [Authorize] and used all the features.
[Authorize(Users = "ABCXYZ")]
public ActionResult About()
{
return View();
}
This blog is for information purpose only. Please contact for any conflict.


