I want my web application to only be reachable from exact IP ranges.
If client IP is not on the range, which is saved in WEB.Config application must deny my access to page.
I want my web application to only be reachable from exact IP ranges.
If client IP is not on the range, which is saved in WEB.Config application must deny my access to page.
Azure Web Apps (formerly Azure Websites) has supported this for a while now. It is a function of IIS and Azure Web Apps makes it available by adding the ipSecurity element to your web.config. You do not need to write any code to do this.
Here is the blog describing the feature for Azure Web Apps and a sample of how to add the configuration to your web.config.
http://azure.microsoft.com/blog/2013/12/09/ip-and-domain-restrictions-for-windows-azure-web-sites/
So how we add these IP ranges to Web.config
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="IP" value="31.171.126.0/255,31.171.127.0/255"/>
</appSettings>
<system.web>
<customErrors mode="Off"/>
<compilation debug="true"/>
<authentication mode="None"/>
</system.web>
</configuration>
How code behind works:
protected void Page_Load(object sender, EventArgs e)
{
var allowed = false;
//Get IP ranges from Web.config
// AS you see in web.config different IP ranges is seperated by comma
var ip = ConfigurationManager.AppSettings["IP"];
// Get Client Ip
lblIp.Text = GetIpAddress().Split(':')[0];
var clientIp = GetIpAddress();
var list = ip.Split(',');
//Do search inside IP ranges and see if client IP is inside IP ranges which is allowed to open web app.
foreach (var item in list)
{
var range = Convert.ToInt32(item.Split('/')[1].ToString(CultureInfo.InvariantCulture));
for (var i=0; i <= range; i++)
{
var submaskip = item.Split('/')[0].Split('.')[0] + "." + item.Split('/')[0].Split('.')[1] + "." +
item.Split('/')[0].Split('.')[2] + "." + i;
if (clientIp == submaskip)
{
allowed = true;
}
}
}
if (allowed == false)
{
Response.Redirect("Denied.aspx");
}
}
// Get Client IP
protected string GetIpAddress()
{
var context = System.Web.HttpContext.Current;
var ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ipAddress)) return context.Request.ServerVariables["REMOTE_ADDR"];
var addresses = ipAddress.Split(',');
return addresses.Length != 0 ? addresses[0] : context.Request.ServerVariables["REMOTE_ADDR"];
}