Tuesday, August 27, 2019

ASP.NET Web API Action Filter with parameters

Bascailly Web API Action Filter is used to add extra logic before or after action method execute, it could be used for authentication, authorization and logging.


Pass the single parameter to Action Filters:

Here is a custom action filter, which is used to authorize the request based on supplied token and accepts single value for Role property

Custom Action Filter:

public class RestrictedAction : ActionFilterAttribute
    {
        public string Role { get; set; }
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var isAuthorized = false;

            IEnumerable<string> values;
            var areHeadersPresent = actionContext.Request.Headers.TryGetValues("X_API_Token", out values);
            ClientData client;

            if (areHeadersPresent)
            {
                client = ClientHelper.GetClient(values.FirstOrDefault());
                if(client.Role == Role)
                {
                    isAuthorized = true;
                }
            }

            if (!isAuthorized)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden, "Unauthorized Access");
            }

            base.OnActionExecuting(actionContext);
        }
    }


Web API Controller:

        [HttpPost]
        [Route("api/Order")]
        [ResponseType(typeof(Order))]
        [RestrictedAction(Role="Admin")]
        public IHttpActionResult SaveOrder(int orderNumber)
        {
            Order order = _orderEngine.SaveOrder(orderNumber);
            if (order == null)
            {
                return BadRequest("Not able to Create a Order");
            }
            return Ok(order);
        }


Pass the multiple parameters to Action Filters:

Here is a custom action filter which accepts collections of values for Role property and error message string

Custom Action Filter:

  public class RestrictedAction : ActionFilterAttribute
    {
        public [] string Role { get; set; }

   public string ErrorMessage { get; set; }

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var isAuthorized = false;

            IEnumerable<string> values;
            var areHeadersPresent = actionContext.Request.Headers.TryGetValues("X_API_Token", out values);
            ClientData client;

            if (areHeadersPresent)
            {
                client = ClientHelper.GetClient(values.FirstOrDefault());
                if(client.Role == Role)
                {
                    isAuthorized = true;
                }
            }

            if (!isAuthorized)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden, ErrorMessage);
            }

            base.OnActionExecuting(actionContext);
        }
    }

Web API Controller:

        [HttpPost]
        [Route("api/Order")]
        [ResponseType(typeof(Order))]
   [RestrictedAction(Role= new string[] { "Admin", "IT" },ErrorMessage= "Unauthorized Access")]       
public IHttpActionResult SaveOrder(int orderNumber)
        {
            Order order = _orderEngine.SaveOrder(orderNumber);
            if (order == null)
            {
                return BadRequest("Not able to Create an Order");
            }
            return Ok(order);
        }

No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...