IP Whitelist Action

public class IpWhitelistAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// Create an IP whitelist
        /// </summary>
        /// <param name="configurationKey">The configuration key that holds the permitted IP's</param>
        public IpWhitelistAttribute(string configurationKey)
        {
			ConfigurationKey = configurationKey;
		}

		public string ConfigurationKey { get; }

		public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            var ip = filterContext.HttpContext.Connection.RemoteIpAddress;
            var config = filterContext.HttpContext.RequestServices.GetService<IConfiguration>();

            var found = false;
            if (config != null)
            {
                var ips = config.GetSection(ConfigurationKey).Get<string[]>();
                
                foreach (var permittedIp in ips)
                {
                    if (!permittedIp.Contains("/"))
                    {
                        if (permittedIp == ip.ToString())
                        {
                            found = true;
                            break;
                        }
                    }
                    else
                    {
                        var netParts = permittedIp.Split('/');
                        if (netParts.Length == 2)
                        {
                            var netIp = IPAddress.Parse(netParts[0]);
                            var netBytes = netIp.GetAddressBytes();
                            var subnetSize = Int32.Parse(netParts[1]);
                            netBytes = netBytes.Take(subnetSize).ToArray();
                            var comparisonAddress = ip.GetAddressBytes().Take(subnetSize).ToArray();

                            if (comparisonAddress.Equals(netIp))
                            {
                                found = true;
                                break;
                            }
                        }
                    }

                }
            }

            if (!found)
            {
                var logger = filterContext.HttpContext.RequestServices.GetService<ILogger>();
                logger.LogWarning($"IP {ip.ToString()} was not permitted access to the service at URL {filterContext.HttpContext.Request.Path}");
                filterContext.Result = new UnauthorizedResult();
            }
        }
    }