5

I need to handle unauthorized exception.. My code is something like:

try
{
 //MY CODE
}
catch (Exception exx)
{
 //My Code
}

I can't understand why if a NOT AUTH exception is thrown, my code didn't pass inside the Exception... UnauthorizedAccessException extends Exception, so WHY this code wont' work?

Thank you very much!

11

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”.

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.

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;
}
2

You can also wrap your code in a using statement like this

using (new SPSecurity.SuppressAccessDeniedRedirectInScope())
    {
        try
        {
            // Code here
        }
        catch (UnauthorizedAccessException ex)
        {
            // code here
        }
    }

Doing so will ensure that the SPSecurity.CatchAccessDeniedException boolean is always set back to its previous state and avoid security leaks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.