Blog

Filter posts by Category Or Tag of the Blog section!

IP filtering attribute for web API

Monday, 02 March 2015

Recently I came up with a solution for filtering the API requests by filtering the server IP. This is used when you want to make the received requests private and secure. It's a simple helper and I hope it could be useful for you as well.


public class AuthorizeApiIPAddressAttribute : ActionFilterAttribute

    {

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)

        {

            //Get users IP Address

            string ipAddress = HttpContext.Current.Request.UserHostAddress;



            if (!IsIpAddressValid(ipAddress.Trim()))

            {

                actionExecutedContext.Response = new System.Net.Http.HttpResponseMessage(HttpStatusCode.Unauthorized);

            }



            base.OnActionExecuted(actionExecutedContext);

        }



        /// <summary>

        /// Compares an IP address to list of valid IP addresses attempting to

        /// find a match

        /// </summary>

        /// <param name="ipAddress">String representation of a valid IP Address</param>

        /// <returns></returns>

        public static bool IsIpAddressValid(string ipAddress)

        {

            //Split the users IP address into it's 4 octets (Assumes IPv4)

            string[] incomingOctets = ipAddress.Trim().Split(new char[] { '.' });



            //Get the valid IP addresses from the web.config

            string addresses = Convert.ToString(AppSettingHelper.GetSetting("AuthorizedIPAddresses"));



            //Store each valid IP address in a string array

            string[] validIpAddresses = addresses.Trim().Split(new char[] { ',' });



            //Iterate through each valid IP address

            foreach (var validIpAddress in validIpAddresses)

            {

                //Return true if valid IP address matches the users

                if (validIpAddress.Trim() == ipAddress)

                {

                    return true;

                }



                //Split the valid IP address into it's 4 octets

                string[] validOctets = validIpAddress.Trim().Split(new char[] { '.' });



                bool matches = true;



                //Iterate through each octet

                for (int index = 0; index < validOctets.Length; index++)

                {

                    //Skip if octet is an asterisk indicating an entire

                    //subnet range is valid

                    if (validOctets[index] != "*")

                    {

                        if (validOctets[index] != incomingOctets[index])

                        {

                            matches = false;

                            break; //Break out of loop

                        }

                    }

                }



                if (matches)

                {

                    return true;

                }

            }



            //Found no matches

            return false;

        }

As you saw, it's an attribute that you can use it in web API.

comments powered by Disqus