SharePoint – Handling Access Denied Exceptions
Recently while working on a project, I ran into an issue with a site that was using forms based authentication (FBA). The application would load configuration settings before the user had logged in. If the application was in a state that the target site’s configuration had not been previously loaded & cached, then the request would be made as an anonymous (null) user. Since some of these settings were stored as SPWeb properties and the unauthenticated user does not have the required permissions the request would be denied and the user was redirected to a page stating that access was denied and they needed to login. The problem was they didn’t have a chance to login yet?!
SharePoint “handles” Access denied exceptions by catching the exception internally and then redirecting the user to a landing page where they can log in to the site. By default this is generally “_layouts/AccessDenied.aspx”.
Most of the time this is an acceptable way for unauthorized exceptions to be handled as you can elevate calls when required in your code. But the scenario does arise where you may need to handle the exception within your own code, not elevate the call and not have the user redirected to an access denied page.
Since SharePoint redirects the request to the default Access Denied landing page you cannot catch the UnAuthorizedAccessException as the redirect causes a ThreadAbortException to be thrown so your code will never get executed.
In order to handle a thrown UnAuthorizedAccessException within your code you first need to set the property CatchAccessDeniedException (part of the SPSecurity class) to false. Doing so means that the Access exceptions aren’t handled by the SharePoint platform and the request isn’t redirected.
The following is some example code.
//It's a good idea to store the original value to be safe.
bool orgcatchvalue = SPSecurity.CatchAccessDeniedException;
try{
SPSecurity.CatchAccessDeniedException = false;
//your code that may throw an authorization exception
}
catch(UnAuthorizedAccessException)
{
//Code to handle exception
}
finally
{
//set the value back to what it was
SPSecurity.CatchAccessDeniedException = orgcatchval;
}With the above example setting CatchAccessDeniedException to false allows you to handle the UnAuthorizedAccessException within your own code without SharePoint redirecting the request.



