Click here to Skip to main content
15,881,812 members
Articles / Web Development / ASP.NET

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

Rate me:
Please Sign up or sign in to vote.
4.88/5 (24 votes)
14 Nov 2006CPOL2 min read 135.1K   1.7K   86   13
Demonstrates how to restrict access to your ASP.NET website by IP address, using an HTTP Module.

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:

C#
/// <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:

XML
<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)


Written By
Technical Lead
United Kingdom United Kingdom
Chris is an ASP.NET MVC tech lead and MCPD with over 12 years' commercial experience producing web-based solutions in a wide range of environments. For the past 8 years he has focused on Microsoft technologies, delivering to major clients in both the public and private sectors.

http://chrisfulstow.com/

Comments and Discussions

 
GeneralMy vote of 5 Pin
shareque19-Sep-14 19:17
shareque19-Sep-14 19:17 
QuestionIIS Problem Pin
meullll31-Oct-12 3:18
meullll31-Oct-12 3:18 
QuestionNot working with IIS Pin
Ritesh Rana31-Oct-12 3:17
Ritesh Rana31-Oct-12 3:17 
AnswerRe: Not working with IIS Pin
User 978032912-Jun-14 3:14
professionalUser 978032912-Jun-14 3:14 
GeneralSystem.StackOverflowException Pin
Yashar Mortazavi31-Jul-12 5:09
Yashar Mortazavi31-Jul-12 5:09 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey7-Jul-12 0:13
professionalManoj Kumar Choubey7-Jul-12 0:13 
GeneralMy vote of 5 Pin
Dmitry Dzygin10-Aug-11 1:45
Dmitry Dzygin10-Aug-11 1:45 
QuestionCan I access session variables from within this? Pin
tmehta13-Mar-10 4:47
tmehta13-Mar-10 4:47 
Can I access session variables from within this?

I need to allow or deny access based on a session variable.
Can I check it from withing the application_beginrequest prcedure?

Nice and simple article.
Thanks,
Generalnot nice Pin
2312 ssxs6-Jun-09 5:29
2312 ssxs6-Jun-09 5:29 
QuestionIntegrate with Ajax Control Tool Kit Pin
Member 272326912-May-09 21:03
Member 272326912-May-09 21:03 
GeneralRe: Integrate with Ajax Control Tool Kit Pin
Member 402265310-May-10 2:56
Member 402265310-May-10 2:56 
GeneralRe: good work Pin
noemailz15-Nov-06 3:07
noemailz15-Nov-06 3:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.