Handle access denied for application pages

1 minute read

Within SharePoint you have the ability to create custom application pages. Application pages remain in the layouts folder of SharePoint. Each user can access these pages by typing in the URL in the explorer bar.

When you would navigate to one of these pages and you do not have enough rights, you would expect that you would be redirected to the access denied page. This is does not happen.

You can try this with a user that has minimal rights and navigate to the following page /_layouts/srchvis.aspx (An out of the box application page for settings the search visibility). You will see that the page gets rendered.

When you create a custom application page you can work around by doing the following:

  protected override void OnLoad(EventArgs e) {
  base.OnLoad(e);

  if (SPContext.Current.Web.UserIsWebAdmin) {
      if (!Page.IsPostBack) {
         //perform your actions
      }
  }
  else {
       SPUtility.HandleAccessDenied(new Exception("You do not have access to this page."));
    }
  } 

In the OnLoad of your page you can check whether the user has sufficient rights. In the example I perform this action by checking if the user is a site admin.

When the user hasn’t sufficient rights you can redirect him to the access denied page of SharePoint by using the HandleAccessDenied() method of the SPUtility class.