Best way to restrict access by IP address?

One way is using a HttpModule.

From the link (in case it ever goes away):

/// <summary>
/// HTTP module to restrict access by IP address
/// </summary>

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 = context.Request.UserHostAddress;
        if (!IsValidIpAddress(ipAddress))
        {
            context.Response.StatusCode = 403;  // (Forbidden)

        }
    }

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

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

Once the HTTP Module class is built you need to register it in the httpModules section of your web.config file, like this:

<configuration>
    <system.web>
        <httpModules>
            <add name="SecurityHttpModule" type="SecurityHttpModule"/>
        </httpModules>
    </system.web>
</configuration>

This adds the module to the ASP.NET request pipeline for your web application.

Leave a Comment