IP address and domain restrictions in ASP.NET
2 answers
Azure Web Apps (formerly Azure Websites) has supported this for a while. This is a feature of IIS and Azure Web Apps that makes it available by adding an ipSecurity element to your web.config. You don't need to write any code for this.
Here's a blog describing this feature for Azure Web Apps, and a sample of how to add configuration to your web.config.
http://azure.microsoft.com/blog/2013/12/09/ip-and-domain-restrictions-for-windows-azure-web-sites/
+2
source to share
So how do 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 the code 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"];
}
0
source to share