Click here to Skip to main content
6,629,885 members and growing! (21,022 online)
Email Password   helpLost your password?
Web Development » ASP.NET » Howto     Intermediate License: The Code Project Open License (CPOL)

Using ASP.NET HTTP Modules to restrict access by IP address

By Chris Fulstow

Demonstrates how to restrict access to your ASP.NET website by IP address, using an HTTP Module.
XML, C# 2.0, Windows, .NET 2.0, ASP.NET, VS2005, Dev
Version:3 (See All)
Posted:14 Nov 2006
Views:33,822
Bookmarked:47 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
15 votes for this article.
Popularity: 5.40 Rating: 4.59 out of 5

1

2
1 vote, 6.7%
3
2 votes, 13.3%
4
12 votes, 80.0%
5

Introduction

This short article demonstrates how to use an ASP.NET HTTP Module to restrict access to your ASP.NET website based on a user's IP address. As you probably know, it's also possible to do this by configuring IIS, as explained in this Microsoft Knowledge Base article: HOW TO: Restrict Site Access by IP Address or Domain Name.

However, if IIS security doesn't give you enough control and flexibility, then you can build your own custom authorisation using an HTTP Module, for example, if you need to look up permitted IP addresses in a database.

What are HTTP Modules?

An HTTP Module lets you add code that will be run every time a page is requested, so it's a great solution for adding custom security checks.

Rather than explain HTTP Modules in detail, I'll point you in the direction of these two MSDN articles for more in-depth information:

Building the HTTP Module

The code for the HTTP Module class is pretty straightforward; it is just a standard .NET class that implements the IHttpModule interface. In this example, an IsValidIpAddress method checks whether the user is connecting from localhost, but this can be modified to suit your own needs.

If the connecting user's IP address isn't valid, then the page will return the HTTP 403 code, indicating to the browser that access to the page is forbidden.

Here the complete HTTP Module code:

/// <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 */ }
}

Registering the HTTP Module

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.

Conclusion

That's all there is to it. There are plenty of other uses for HTTP Modules, such as:

  • Adding custom headers and footers to content
  • Logging and collecting statistics
  • Custom caching mechanisms
  • User authentication

Experiment and have fun!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Chris Fulstow


Member
Chris is a software developer and Microsoft Certified Technology Specialist with over 9 years' commercial experience producing web-based solutions in a wide range of environments. For the past 6 years he has focused on Microsoft technologies, delivering to major clients in both the public and private sectors.

http://chrisfulstow.blogspot.com/
Occupation: Web Developer
Location: United Kingdom United Kingdom

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 4 of 4 (Total in Forum: 4) (Refresh)FirstPrevNext
Generalnot nice Pinmember2312 ssxs6:29 6 Jun '09  
QuestionIntegrate with Ajax Control Tool Kit PinmemberMember 272326922:03 12 May '09  
Generalgood work PinmemberMinhajkk2:57 15 Nov '06  
GeneralRe: good work Pinmembernoemailz4:07 15 Nov '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 14 Nov 2006
Editor: Smitha Vijayan
Copyright 2006 by Chris Fulstow
Everything else Copyright © CodeProject, 1999-2009
Web21 | Advertise on the Code Project