Search This Blog

Wednesday, August 17, 2011

Block IP address from any accessing website (asp.net)


One way direct web.config file put following code

<configuration>
<system.web>
<system.webServer>
    <security>
      <ipSecurity allowUnlisted="true">
       
        <clear/>
       
       
        <add ipAddress="192.168.1.8"/>
       
        <add ipAddress="192.168.1.8" subnetMask="255.255.255.0"/>
       
      ipSecurity>
    security>
    <modules runAllManagedModulesForAllRequests="true"/>
  system.webServer>
system.web>
configuration>

Other way
xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
       <appSettings/>
       <connectionStrings/>
       <system.web>
              <httpModules>
                     <add name="SecurityHttpModule" type="SecurityHttpModule"/>
              httpModules>
              <compilation debug="true" targetFramework="4.0"/>
              <authentication mode="Windows"/>
              <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>system.web>
configuration>


And add on App_Code folder one HTTP module class file like “SecurityHttpModule.cs”
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;

///

/// HTTP module to restrict access by IP address
///

public class SecurityHttpModule : IHttpModule
{
       public SecurityHttpModule() { }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(Application_BeginRequest);
    }

    private void Application_BeginRequest(object source, EventArgs e)
    {
        //HttpContext context = ((HttpApplication)source).Context;
        string ipAddress = GetIPAddress();
        if (IsValidIpAddress(ipAddress))
        {
            //context.Response.StatusCode = 403;  // (Forbidden)
            Response.Redirect("Default2.aspx");
        }
    }

    private bool IsValidIpAddress(string ipAddress)
    {
        return (ipAddress == "192.168.1.3");
    }

    public void Dispose() { /* clean up */ }


    public static string GetIPAddress()
    {
        string hostName = Dns.GetHostName();
        IPAddress address = Dns.Resolve(Dns.GetHostName()).AddressList[0];
        return address.ToString();
    }
   
}


No comments: