Friday 15 August 2008

Prevent users from viewing Application Pages

As a part of security measure, we have been asked to restrict the people accessing the default application pages like /Forms/Allitems.aspx,/_layouts/mcontent.aspx, Userdisp.aspx.
I ve heard about viewlockdownfeature but also heard that there are some issues with that. So I thought we can do this task by a custom http handler.
In order to make this handler configurable instead of hardcoding the URL's I made an entry in node of web.config file and redirect those URL's to desired page.
The code for Http Handler goes like this :

******************************************************************
// Description:
// This HTTP handler redirects the Application pages to desired page defined in <AppSettings>node in web.config file
//
// Implementation :
//<httpModules>
//<add name="ReRoutePages" type="muki.ReRouteAppPages, ForceSSL,Version=1.0.0.0, Culture=neutral,PublicKeyToken=XXXXX" />
//</httpModules>
//<appsettings>
//<add key ="ApplicationPages" value="/Forms/AllItems.aspx,/_layouts/settings.aspx"/>
//<add key ="AdminPagesReRoutedURL" value ="http://servername/Pages/DontSeethosePages.aspx"/>
//</appsettings>

*******Code begins***********************
namespace muki
{
class ReRouteAppPages : System.Web.IHttpModule
{
#region IHttpModule Members

public void Dispose()
{
throw new NotImplementedException();
}

public void Init(System.Web.HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}

#endregion
void context_BeginRequest(object sender, EventArgs e)
{
ReRoutePages(System.Web.HttpContext.Current.Request.Url.PathAndQuery);
}
public void ReRoutePages(string pageURL)
{
//check for the current page exists in the group of pages requiring ReRouting
//if page is found in ReRoute group then redirect page to desired page as per web.config entry
try
{
bool found = false;
string AppPages = System.Configuration.ConfigurationSettings.AppSettings["ApplicationPages"];
string destURL = System.Configuration.ConfigurationSettings.AppSettings["AdminPagesReRoutedURL"];
char[] separator;
separator = new char[] { ',' };
string[] pages;
pages = AppPages.Split(separator);

for (int i = 0; i < pages.Length; i++)
{
if (pageURL.ToLower().Contains(pages[i].ToLower()))
{
found = true;
break;
}
}
if (found)
{
HttpContext.Current.Response.Redirect(destURL);
}

}
catch (Exception ex)
{

HttpContext.Current.Response.Write("An error has occured in ReRouting Application Pages" + ex.InnerException.ToString());
}

}
}
}

******************************************************************

2.Strong Name the assembly and GAC it.
3.Refer the Implementation
4.Perform IISReset.

We are done right!

No comments: