Tuesday, August 24, 2004

 

Role of HTTP Modules in .NET Security

Summary

ASP.NET provides an exhaustive Framework support for customized server-side programming.One should have the complete knowledge on how the Web Requests are getting processed by the Pipeline objects (Http Application,Http Handlers , Http Modules)to develop an efficient and highly secure web applications.This article explains in detail about the HTTP Modules and the steps to create custom Http Module with an example. The article also gives a brief on how to create a custom Http Module in developing a custom database authorization module.

Introduction

Today, one of the important goals is to provide high security to the 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 the 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 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 custom Http Module with an example. The article also gives a brief 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

A HTTP Module is basically a class which Implements IHTTPModule Interface to pre/post processes the Web Requests.The built-in modules in the 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 also new modules can 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 Create and Implement Custom Http Module with an Example


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
ii) Map the Key file to the AssemblyKeyFile attribute in the AssemblyInfo.cs
iii) 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 DBAuthorization 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 Authorization module and there are several interesting Modules to be explored and can be customized to suit business needs like custom authentication, caching and state management.

References

http://support.microsoft.com/default.aspx?scid=kb;en-us;307985
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpatterns/html/ImpInterceptingFilterInASP.asp
http://msdn.microsoft.com/msdnmag/issues/02/09/httppipelines/
http://support.microsoft.com/default.aspx?scid=kb;EN-US;308000


This page is powered by Blogger. Isn't yours?