Secure application pages in Sharepoint applications

For SharePoint applications, some times we have to create ASP.NET Application pages that reside under the _layouts folder and are not managed by SharePoint Security system.

We have to secure them manually by code, one way is to check in Page_Load and disable controls if necessary.

protected void Page_Load(object sender, EventArgs e)
        {
            if (!UserIsAuthorized)
            {
                //hide the form
                //show an error message
            }
}

Make sure to check if user is authorized in critical methods.

To check if user is authorized:

protected UserIsAuthorized
{
   get
  {
      SPUser  user = SPContext.Current.Web.CurrentUser;

     if(user==null) return false;//anonymous/public users

     //check if user belongs to authorized groups
            string[] validGroups = new string[] { “Group A”, “Group B };
            SPGroupCollection groups = user.Groups;
            foreach (SPGroup group in groups)
                if (validGroups.Contains(group.Name))
                    return true;

    //check if user is System Account
    if (user.ID == SPContext.Current.Web.Site.SystemAccount.ID)
                return true;

    return false;//user is not authorized;
   }
}

Leave a Reply

Your email address will not be published. Required fields are marked *