Role of HTTP Modules in .NET Security






4.11/5 (9 votes)
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 startsApplication_AuthenticateRequest
- Authenticate the CallerApplication_AuthorizeRequest
- Checks the privileges for the CallerApplication_ResolveRequestCache
- To get a response from the cacheApplication_AcquireRequestState
- To Load Session StateApplication_PreRequestHandlerExecute
- Fired before the request is sent to the handler objectApplication_PostRequestHandlerExecute
- Fired after the request is sent to the handler objectApplication_ReleaseRequestState
- To release the Session StateApplication_UpdateRequestCache
- To update the Response CacheApplication_EndRequest
- Fired after processing endsApplication_PreSenRequestHeaders
- Fired before buffered response headers are sentApplication_PreSendRequestContent
- Fired before buffered response body is sentApplication_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
- To register the Event Handlers for
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:
- Create a Strong Name Key file
sn –k key.snk
- Map the Key file to the
AssemblyKeyFile
attribute in the AssemblyInfo.cs 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
- INFO: ASP.NET HTTP Modules and HTTP Handlers Overview
- MSDN Magazine
- How To Create an ASP.NET HTTP Module Using Visual Basic .NET
History
- 22nd May, 2007: Initial post