How To Secure Sharepoint Application Pages By User Group



TODO:

Have you ever wanted to secure an Sharepoint Application Page by User Group?  If so, just use the method below, and call it in Page_Load.

 

SOLUTION:

/// <summary>
/// Validate that the page can be accessed
/// </summary>
/// <returns></returns>
protected void ValidatePageAccess(string[] AllowedUserGroups)
{
     try
     {
          //get web object
          using (SPWeb currentWeb = this.Web)
          {                    
               #region Allowed Groups

               SPGroup allowedGroup = null;
               bool userHasAccess = false;

               //check each, if one group is OK, all are.
               foreach (string group in AllowedUserGroups)
               {
                   allowedGroup = currentWeb.Groups[group];

                   //see if user is in allowed group
                   if (allowedGroup.ContainsCurrentUser)
                   {
                       if (Request.HttpMethod == "POST")
                       {
                           SPUtility.ValidateFormDigest();
                       }
                       userHasAccess = true;
                       break;
                   }
               }
               
               //now check access
               if(!userHasAccess)
               {
                    throw new Exception("User does not have access");
               }
               #endregion 
          }
     }
     catch (Exception x)
     {
          Response.Redirect("/_layouts/accessdenied.aspx");
     }
}

 

NOTES:

There are no notes on this topic.



Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading