Wednesday, July 20, 2011

Customizing SharePoint 2007 "Access Denied" Page

In SharePoint 2010, we can run the powershell command below to "tell" SharePoint that we have our own "Custom Access Denied" page & which web applications should use that custom page.

Set-SPCustomLayoutsPage -Identity <None | AccessDenied | Confirmation | Error | Login | RequestAccess | Signout
| WebDeleted> -RelativePath <String> -WebApplication <SPWebApplicationPipeBind>
[-AssignmentCollection <SPAssignmentCollection>] [-Confirm [<SwitchParameter>]] [-WhatIf [<SwitchParameter>]]

However, we don't have the same feature in SharePoint 2007. Below is a workaround to achieve just that. Explanation follows.

1. First make a backup copy of out of box version of the  AccessDenied.aspx file. Keep it safe somewhere.

2. Open the Accessdenied.aspx file in your favourite editor (Notepad? Visual Studio?)

3. Insert the code below in the file between the last register statement line and content place holder code

<script runat="server">

protected void Page_Load(object sender, EventArgs e)
{
string strIncoming = Page.Request.Url.AbsoluteUri.ToLower();

string strTargetURL = "";
string strSource = Request.QueryString["Source"];
string strType = Request.QueryString["type"];
string strQuery = "";

///Check if its customized web apps
if (IsCADeniedWebApp(strIncoming))
{

//check  if user is trying to sign in as another user
if (!strIncoming.Contains("loginasanotheruser"))
{
strQuery = "Source=" + strSource + "&Type=" + strType;
strTargetURL = "/_layouts/<your custom folder>/<your custom page>" + strQuery;

SPUtility.Redirect(strTargetURL, SPRedirectFlags.Default, HttpContext.Current);
}
}
}

private bool IsCADeniedWebApp(string strURL)
{
try
{
string strWebApp = "";
string[] arrWebApps = File.ReadAllLines("C:\\Program Files\\Common Files\\Microsoft Shared\\Web Server Extensions\\12\\TEMPLATE\\LAYOUTS\\<your custom folder>\\CustomisedWebApps.txt");
int intNumberOfWebApps = arrWebApps.Length;

for (int i = 0; i < intNumberOfWebApps; i++)
{
if (arrWebApps[i] != null)
{
strWebApp = arrWebApps[i].Trim();
if (strWebApp != "")
{
if (strURL.Contains(strWebApp))
return true;
}
}
}

return false;
}
catch (Exception ex)
{
return false;
}
}
</script>

The code makes use of a text file which contains the list of web apps that will use the customized access denied page.

Basically, the code above will check for 2 conditions.

i) if the URL that user accessing belongs to a web apps that uses customized access denied page. If not, just ignore it.

ii) if user is trying to login as another user.  For some reason, MS is re-using the AccessDenied.aspx to handle "signing in as another user".

If, the URL belongs to the web apps that uses customized access denied page and user is not trying to sign in as another user, the code will redirect the user to another page. this is where you need to add your custom code.In my case, i will display the list of users with full control to the site or resource.