|
||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
Note: This is an unedited contribution. If this article is inappropriate,
needs attention or copies someone else's work without reference then please
Report This Article
IntroductionThis 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 ModuleThe code for the HttpModule class is pretty straightforward, it just a standard .NET class that implements the IHttpModule interface. In this example, an 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 ModuleOnce the HttpModule 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. ConclusionThat's all there is to it. There are plenty of other uses for HTTP Modules, such as:
Experiment and have fun!
|
|||||||||||||||||||||||||||||||||||||||||||||||