For programmers, testers and tech geeks

Custom authorization using AuthorizeAttribute Filter MVC

Authorization in MVC with Authorization Filter is awesome thing. In MVC context controllers are all our resources for user more often i.e. users interact with our application using url and in MVC a url is mapped with our controllers and that's all. A controller is also consists of number of actions which are also used in url call. The point here is why not we should filter users requests to our resources and using a filter whole controller can be checked for a particular user (based on username, role or any thing ) as well as an individual action inside a MVC4 provides basic filters implementation in default template but we are going to do something different.
There are basically four types of filter that MVC offers:
  1. Authorization Filter
  2. Action Filter
  3. Result Filter
  4. Exception Filter
Today we are only going with Authorization Filter ( basically going to customize it )
There is a class AuthorizeAttribute which implements IAuthorizationFilter, this class has two very important methods:
protected virtual bool AuthorizeCore(HttpContextBase httpContext)

protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext)

And we are going to override these methods. So start following steps described below:
 1.  Create a class with suffix "Attribute" , and inherit it from AuthorizeAttribute class e.g                                                                     
public class UAuthAttribute: AuthorizeAttribute {
2. Constructor with array of string  
private string[] Roles;   public UAuthAttribute(params string[] Roles){                                                                                                             this.Roles = Roles;
3. Override methods described above like this
protected override bool AuthorizeCore(HttpContextBase httpContext)
            bool isAuthenticated = httpContext.Request.IsAuthenticated;
            // get the current user role by its name just an idea , do whatever you want
            string CurrentUserRole="Admin";//httpContext.User.Identity.Name
            bool AuthorizeRole = Roles.Contains(CurrentUserRole, StringComparer.InvariantCultureIgnoreCase);
            return isAuthenticated && !AuthorizeRole;
        // un-authorize case handler
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
            filterContext.HttpContext.Response.Redirect("~/"); // by default it is redirected to the login page
4. HandleUnauthorizedRequest method is optional, is describes what to do if authorization fails, by default in case of failure user is redirected to log in page but we can override that behavior and redirect to some custom page or any where we want.
5. Fifth and last thing is how to use this now, to use that filter just call it on top of the Action as shown below or you can also use it on top of controller which will be applicable for all its actions.
             public ActionResult Contact()
                ViewBag.Message = "Your contact page.";
              return View();

That is how we can use Authorization Filter to authorize users on the basis of their roles,names etc
I hope this little introduction helps for your further exploration.