Click here to Skip to main content
Click here to Skip to main content

Role of HTTP Modules in .NET Security

, 22 May 2007
Rate this:
Please Sign up or sign in to vote.
Custom Authorization using HTTP Modules

Introduction

Today, one of the important goals is to provide high security to distributed Web Applications. The security is designed throughout the .NET Framework like Code Access Security, ASP.NET Integrated Security and Cryptography, which can be optimally used to develop Secure Applications.

However, in scenarios where one has to perform Authentication or Authorization by the database and give appropriate privileges to the users (or) the permissions have to be provided at runtime for specific operations (or) in scenarios like where no Web browsers are used, it becomes crucial to develop Custom Security.

The ASP.NET Framework has defined a set of HTTP Modules which takes care of the basic Authentication and Authorization mechanisms. The Custom Security (Custom Authentication or Authorization) can be performed in Forms Authentication or Windows Authentication by coding in the Global.asax file, which is not a reliable (or) reusable solution. The .NET Framework gives the flexibility to develop custom HTTP Modules and plug them into the ASP.NET Application, hence enabling to develop highly scalable, reusable and reliable .NET Security Components.

This article explains in detail about the HTTP Modules and the steps to create a custom HTTP Module with an example. The article also gives a brief about how to create a custom HTTP Module in developing a custom database authorization module.

ASP.NET Pipeline Processing

When a Web request for a page is raised, it gets processed by ASP.NET Pipeline Objects. First the request is received by HTTP Runtime Object from the IIS and gets directed to the respective HTTP Application object. Further, the request gets filtered by various HTTP Module objects such as Windows Authentication Module, Session Module and finally gets processed by HTTP Handler object. The Current request information can be accessed anywhere in the pipeline through the HTTP Context Object.

HTTP Modules

An HTTP Module is basically a class which Implements IHTTPModule Interface to pre/post process the Web requests.

The built-in modules in ASP.NET are:

  • Output Cache Module
  • Windows Authentication Module
  • Forms Authentication Module
  • Passport Authentication Module
  • URL Authorization Module
  • File Authorization Module

The implementation of these modules can be customized and new modules can also be added to enhance more security features by developing Custom HTTP Modules. As an example, we can develop a custom authentication module to authenticate users via Active Directory services.

The modules get executed when an HTTP Application Event is raised. The HTTP Application Events are listed as follows:

HTTP Application Events

  • Application_BeginRequest - Fired before request processing starts
  • Application_AuthenticateRequest - Authenticate the Caller
  • Application_AuthorizeRequest - Checks the privileges for the Caller
  • Application_ResolveRequestCache - To get a response from the cache
  • Application_AcquireRequestState - To Load Session State
  • Application_PreRequestHandlerExecute - Fired before the request is sent to the handler object
  • Application_PostRequestHandlerExecute - Fired after the request is sent to the handler object
  • Application_ReleaseRequestState - To release the Session State
  • Application_UpdateRequestCache - To update the Response Cache
  • Application_EndRequest - Fired after processing ends
  • Application_PreSenRequestHeaders - Fired before buffered response headers are sent
  • Application_PreSendRequestContent - Fired before buffered response body is sent
  • Application_Error - Fired when an error is raised

The IHTTP Module has the following two methods:

  • Init( HttpApplication objApplication)
    • To register the Event Handlers for HttpApplication events
  • Dispose()
    • To release the resources

Steps to Implement Custom HTTP Module

1. Create a Class Implementing IHTTPModule Interface

The Init Method taking HttpApplication Object as parameter and Dispose methods are declared:

//using System; 
//using System.Web; 
//namespace CustomModule 
//{ 
//public class CustomAuthnModule : IHttpModule 
//{ 
//public CustomAuthnModule() 
//{ 
//} 
//public void Init(HttpApplication objHttpApp) 
//{ 
//} 
//public void Dispose() 
//{ 
//} 
//} 
//} 

2. Register the Events in the Init Method of the Class

Register the EventHandler for the Event that needs to be handled:

//public void Init(HttpApplication objHttpApp) 
//{ 
//objHttpApp.AuthenticateRequest+=new EventHanlder(this.CustomAuthentication); 
//} 

3. Write the Method Code to Handle the Registered Event

When the Authentication Request is raised, the CustomAuthentication method gets executed. In this example, it gives response of message when the event is raised.

//private void CustomAuthentication (object sender,EventArgs evtArgs) 
//{ 
//HttpApplication objHttpApp=(HttpApplication) sender; 
//objHttpApp.Context.Response.Write("Custom Authentication Module is Invoked"); 
} 

4. Install the Library File into GAC...

... (or) Place it in bin directory of the Web Application which makes use of the developed Custom Module.

Steps to Install the DLL in GAC:

  1. Create a Strong Name Key file
    sn –k key.snk
  2. Map the Key file to the AssemblyKeyFile attribute in the AssemblyInfo.cs
  3. gacutil /i CustomModule.dll

5. Register the HTTPModule

The HTTP Modules have to be registered in the Web.config file of the Application which implements them. The Configuration details for the httpModules is given below:

<httpModules>
<add name ="ModuleName" type="Namespace.ClassName","AssemlbyName">
</add ></httpModules>

In this example, the Module Name is CustomAuthnModule, Namespace is CustomModule and the AssemblyName is CustomModule. Hence the configuration for the custom Module is as shown below:

<httpModules>
<add name="CustomAuthnModule" type="CustomModule.CustomAuthnModule,CustomModule">
</add>
</httpModules>

An Example - Custom DB Authorization Module

Scenario

ABC Company has to develop an Internet application for the various business partners doing business with them.The information about the business partners and their respective privileges are stored in the SQL Server database. One of the requirements is to validate the users and populate the roles at the database level and to provide appropriate access to the application.The code given below helps to achieve the given requirement.
When the Web page ViewBusinessPartners.aspx is requested with the "request User Parameter", it validates the User privileges to access the requested site and gives appropriate access.

Complete Code

using System; 
using System.Web; 
using System.Data; 
using System.Data.SqlClient; 
namespace CustomAuthorizationModule 
{ 
public class CustomAuthorizationModule : IHttpModule 
{ 
public CustomAuthorizationModule() 
{ 

} 
public void Init(HttpApplication objApp) 
{ 
objApp.AuthorizeRequest += new 
EventHandler(this.CustomDBAuthorization); 
} 
public void Dispose() 
{ 
} 
private void CustomDBAuthorization(object sender,EventArgs 
evtArgs) 
{ 
HttpApplication objApplication =(HttpApplication)sender; 
string sAppPath,sUsrName; 
bool bAuthorized = false; 
sAppPath=objApplication.Request.FilePath.ToString(); 
sUsrName=objApplication.Request.Params[0].ToString(); 
bAuthorized = DBAuthorize(sUsrName,sAppPath); 
if(bAuthorized) 
{ 
objApplication.Context.Response.Write("Authorized User"); 
} 
else 
{ 
objApplication.Context.Response.Write("UnAuthorized User"); 
objApplication.Response.End(); 
} 
} 
private string DBAuthorize(string sUsrName,string sAppPath) 
{ 
SqlConnection sqlConn=new SqlConnection()
sqlConn.ConnectionString="user id=sa;Pwd=password;Data Source=localhost;
    Initial Catalog=Northwind"); 
SqlCommand sqlCmd=new SqlCommand(); 
SqlParameter sqlParam=new SqlParameter(); 
sqlCmd.Connection=sqlConn; 
sqlConn.Open(); 
sqlCmd.CommandType=CommandType.StoredProcedure; 
sqlCmd.CommandText="sAuthorizeURL"; 
sqlParam = sqlCmd.Parameters.Add ("@UserName",SqlDbType.VarChar,30); 
sqlParam = sqlCmd.Parameters.Add("@URLPath",SqlDbType.VarChar,40); 
sqlCmd.Parameters["@UserName"].Value=sUsrName; 
sqlCmd.Parameters["@URLPath"].Value=sAppPath; 
string res=sqlCmd.ExecuteScalar().ToString(); 
if(res == "Authorized") 
{ 
return true; 
} 
else 
{ 
return false; 
} 

} 
} 
} 

Conclusion

The role of HTTP Modules in .NET Security is to filter and process the Web requests. It also helps to build high security in the Web Applications by developing custom modules. This article has explored only the Authorization module. There are several interesting Modules to be explored and can be customized to suit business needs like custom authentication, caching and state management.

References

History

  • 22nd May, 2007: Initial post

License

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

About the Author

VanithaGanesan
Web Developer
United States United States
VanithaGanesan is a software professional skilled in .NET,SQL Server,Oracle and Formware products.She has a Master degree in Computer Application and holds MCSD.NET certification.

Comments and Discussions

 
GeneralMy vote of 5 Pinmembershek1244-Apr-12 21:32 
GeneralEach request will hit database. Pinmemberlax4u13-Nov-08 15:15 
GeneralExcellent PinmemberAnand Vismaad22-Aug-07 20:15 
GeneralGlad to know that. PinmemberBruce Y. Lee29-May-07 0:04 
QuestionUsing it to validate Client Certificates? PinmemberM.K.A. Monster23-May-07 0:20 
Hi,
 
Do you think it is possible to use this kind of security through HTTP Modules, using Client Certificates? By requesting a Client Certificate and validating it in the request.
 
Yours,
 
Mark Monster
AnswerRe: Using it to validate Client Certificates? PinmemberVanithaGanesan23-May-07 3:24 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 22 May 2007
Article Copyright 2007 by VanithaGanesan
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid