Authorization filters : These implement IAuthorizationFilter and make security decisions about whether to execute an action method, such as performing authentication or validating properties of the request.

This post demonstrates how to create a custom authorization filter.

Step 1 : Create the Authorization Attribute and Filter:

///marker attribute
public class CustomAuthorizeAttribute : FilterAttribute { }

//filter
public class CustomAuthorizeFilter : IAuthorizationFilter
{
      private readonly ICustomerService _customerService;
      public CustomAuthorizeFilter(ICustomerService userService)
      {
          _customerService = userService;
      }

      public override void OnAuthorization(AuthorizationContext filterContext)
      {
          var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
          var actionName = filterContext.ActionDescriptor.ActionName;

          var authorized = false;
          var routeValues = GetRouteDataValues();
          int id = routeValues["id"] == null ? 0 : int.Parse(routeValues["id"].ToString());

          // build your custom logic using 
          // controllerName, actionName and id to set the 'authorized' flag.

          if(!authorized)
          {
              HandleUnauthorizedRequest(filterContext);
          }
      }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        Elmah.ErrorSignal.FromCurrentContext().
          Raise(new Exception("403 forbidden - " + filterContext.RequestContext.HttpContext.Request.RawUrl, null));
        filterContext.HttpContext.Response.StatusCode = 404;
        filterContext.Result = new ViewResult
        {
            ViewName = "~/Views/Error/PageNotFound.cshtml"
        };
    }

      public Dictionary<string, object> GetRouteDataValues()
      {
          return new Dictionary<string, object>(_contextBase.Request.RequestContext.RouteData.Values);
      }
}

Step 2: Binding:

this.BindFilter<CustomAuthorizeFilter>(System.Web.Mvc.FilterScope.Controller, 0).WhenActionHas<CustomAuthorizeAttribute>();

Step 3 : Decorate your Actions with the filter:

public class AccountController : Controller
{
    [CustomAuthorizeAttribute]
    public ActionResult MyPreciousAction()
    {
        // beep beep bepp ;)
    }
}

You may want to refer the below links I had used while creating this blog post. Cheers !

References: