Friday, July 6, 2018

Check if request IP address is in the allowed list

If we want to check if the IP address of mvc request if within a valid ip addresses list, we can do so by using "REMOTE_ADDR" header.

Lets say our ip addresses are saved in a string list
List<string> IPAddresses;

Then we could use a method like this to authenticate inside a custom ActionFilterAttribute


protected virtual bool IsAuthentic(AuthenticationChallengeContext filterContext)
        {
            if (IPAddresses.Length > 0)
            {
                var ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                if (!string.IsNullOrWhiteSpace(ip) && !((Mode == IPRestrictAttributeModes.Allow) == (IPAddresses.Any(addr => parse(addr).Equals(parse(ip))))))
                {
                    // The user is not in any of the listed ips =>
                    // show the unauthorized view
                    filterContext.Result = new ViewResult
                    {
                        
                        ViewName = "~/Views/Shared/Unauthorized.cshtml"
                    };
                    return false;
                }
            }
           
            return Mode == IPRestrictAttributeModes.Deny;
        }


The parse method parses ip address from string which is


// This method calls the IPAddress.Parse method to check the ipAddress
        // input string. If the ipAddress argument represents a syntatically correct IPv4 or
        // IPv6 address, the method displays the Parse output into quad-notation or
        // colon-hexadecimal notation, respectively. Otherwise, it displays an
        // error message.
        private static IPAddress parse(string ipAddress)
        {
            try
            {
                // Create an instance of IPAddress for the specified address string (in
                // dotted-quad, or colon-hexadecimal notation).
                IPAddress address = IPAddress.Parse(ipAddress);

                // Display the address in standard notation.
                //Console.WriteLine("Parsing your input string: " + "\"" + ipAddress + "\"" + " produces this address (shown in its standard notation): " + address.ToString());
                return address.MapToIPv4();
            }

            catch (ArgumentNullException e)
            {
                throw;
            }

            catch (FormatException e)
            {
                throw;
            }

            catch (Exception e)
            {
                throw;
            }
            return null;
        }

No comments:

c# httpclient The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch

 If we get this error while trying to get http reponse using HttpClient object, it could mean that certificate validation fails for the remo...