Not to be confused with SharePoint groups; Roles, also known as Permission Levels or Role Definitions, are logical groupings of base permissions. These are typically assigned to SharePoint Groups but can also be assigned to individual users. Some samples of out-of-the-box roles or permission levels include; Read, Contribute, Design, Full Control, and Limited Access.

The following code demonstrates how to verify if the current user is in a particular role or has been assigned a specific permission level. The code sample uses SPContext.Current to get a reference to the current site, as such it must be ran under the context of SharePoint (in a web part, or custom application page), to run the code in a console application or windows application you will need to change how the reference to the SPWeb object is obtained.

SPWeb web = SPContext.Current.Web;

//****************************************
// Validate the page request to avoid
// any malicious posts
if (Request.HttpMethod == “POST”)
   SPUtility.ValidateFormDigest();

//****************************************
// Get a reference the roles that are
// bound to the current user and the role
// definition to which we need to verify
// the user against
SPRoleDefinitionBindingCollection usersRoles = web.AllRolesForCurrentUser;
SPRoleDefinitionCollection roleDefinitions = web.RoleDefinitions;
SPRoleDefinition roleDefinition = roleDefinitions[“Full Control”];

// Check if the user is in the role. If not
// redirect the user to the access denied page
if (usersRoles.Contains(roleDefinition))
{
   //*******************************
   //Check if post back to run
   //code that initiates the page
   if (IsPostBack != true)
   {
    //Do your stuff here
   }
}
else
{
   Response.Redirect(“/_layouts/accessdenied.aspx”);
}

Advertisements