Ehsan Ghanbari

Experience, DotNet, Solutions

IP filtering attribute for web API

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.

About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
Peridic pattern
How to use PagedList In asp.net MVC
Redis as a cache server
Domain driven design VS model driven architecture
How to query over Icollection<> of a type with linq
What's the DDD-lite?
comments powered by Disqus