Working with Custom Authorize Attribute in MVC

Dheeraj Kumar Gunti

Reading Time : ( words)


Extending Authorize attribute will allow you to create a nice scope of accessibility in application. For example if I need to restrict users to create an employee, I can restrict using custom filters and authorize attribute. Following is the small example of how we can achieve this.

AuthorizeAttribute class is inherited from IAuthorizeAttribute and FilterAttribue which has certain methods and properties which can be extended to achieve custom results.

There are few methods which will be useful and which should be overridden for achieving this functionality.

AuthorizeCore - This method is the entry point of authorization. Here you can check whether the user is authorized or not. and can even apply custom logic.

HandleUnauthorizedRequest - This method is used to redirect the request if unauthorized to a different page.

Following is a small example:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
}

Here I have created a custom class named: CustomAuthorizeAttribute, which is inheriting from AuthorizeAttribute.

I am creating a privileges list which holds some temp privileges. Here in this scenario you can get the privileges from other source if you have different functionality. Like getting data from Database or some collection.

string[] customPriveleges = new string[] { "Create", "Read" };

I am overriding AuthorizeCode method and extending that to accomplish a custom logic to check whether the logged in user has authorized to access or not.

public string AccessPermission { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    var isAuthorized = base.AuthorizeCore(httpContext);
    if (!isAuthorized)
    {
    return false;
    }
    int pos = Array.IndexOf(customPriveleges, this.AccessPermission);
    if (pos > -1)
    {
    return true;
    }
    else
    {
    return false;
    }
}

In the above code, Initially I am checking whether the user is authorized or not. If not it will redirect to Custom Error Page.

The Initial Authorization is to check whether user is authenticated or not, Once authentication is done then the next step which identifies whether he is authorized to access this page or not. Based on the privileges that we defined it validates. If he is not authorized then request will be redirected to custom error page.

here is how we specify the authorization attribute.

[CustomAuthorize(AccessPermission = "Create")]
public ActionResult Index()
{
    return View();
}

We override one more method which handles the redirection of request to custom error page.

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { action = "Index", controller = "Error" }));
}

In the above method, when unauthorized it will be redirected to Index Action in Error Controller.