ASP.NET中的IP地址和域限制

时间:2015-05-19 12:43:16

标签: asp.net azure web-config azure-web-sites ip-restrictions

我希望我的Web应用程序只能从确切的IP范围内访问。

如果客户端IP不在范围内,则保存在WEB.Config应用程序中,必须拒绝我访问页面。

2 个答案:

答案 0 :(得分:2)

Azure Web Apps(以前称为Azure网站)已经支持了一段时间了。它是IIS的一项功能,Azure Web Apps通过在web.config中添加 ipSecurity 元素使其可用。您不需要编写任何代码来执行此操作。

以下是介绍Azure Web Apps功能的博客,以及如何将配置添加到web.config的示例。

http://azure.microsoft.com/blog/2013/12/09/ip-and-domain-restrictions-for-windows-azure-web-sites/

答案 1 :(得分:0)

那么我们如何将这些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"];
}