Sunday 5 October 2014

Prevent direct access to a resource by using an HttpModule , asp.net MVC 4 C#

In asp.net MVC, resource  is  an action of a controller.
Before the asp.net MVC engine returns the resource to the user, a route mechanism manages to way how to look the physical resource from the url.
For example , I currently host a default MVC solution under IIS and each of the following URL is a resource :

http://localhost:9088/ =>  it should be the default route
http://localhost:9088/Home/Contact/8 => try to get the action Contact of the Home controller for the contact Id = 8

The navigation through the "intranet" site would be simpler and safer if the user could not access directly a resource by changing the url address, in this case, he will be redirected to an error page.

One way to prevent this behavoir is to use :
- a custom HttpModule : which checks all incoming requests at the stage of the BeginRequest event
- the http header "Referer" which contains the previous url from which the current request comes from.
We should also consider the case of the first access to the site, normaly it should be the something like http://my-web-site{:port}/

In this lab, I will use the default template "MVC internet application", it already contains some functional resources.

The first step is to create a module.
1- Add a file named DirectAccessModule.cs into the project.
The make it a module, simply inherits the class from IHttpModule.



To register the module, add or update the following section in the web.config  :
 <modules runAllManagedModulesForAllRequests="true" >
      <add name="DirectAccessModule" type=" Devenva.Demo.Solution.DirectAccess.DirectAccessModule, Devenva.Demo.Solution.DirectAccess"/>
    </modules>
At this point, the application is ready to prevent direct access.