我希望我的web应用程序只能从确切的IP范围访问。
如果客户端IP不在范围内,则保存在WEB中。配置应用程序必须拒绝我访问页面
Azure Web Apps(以前的Azure网站)已经支持此功能一段时间了。它是IIS和Azure Web应用程序的一个功能,通过在Web .config中添加ipSecurity元素可以使用它。您不需要编写任何代码来执行此操作。
这是描述Azure Web应用程序特性的博客,以及如何将配置添加到Web .config的示例。
http://azure.microsoft.com/blog/2013/12/09/ip-and-domain-restrictions-for-windows-azure-web-sites/那么我们如何将这些IP范围添加到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>
后台代码如何工作:
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"];
}