Create and Assign Custom Permission levels programatically in SharePoint

Sometimes, we come across a business requirement, where in:

We need to create SharePoint sites on the fly (maybe using a site definition), which have their own unique permission and groups.
We might need to create a custom permission level for the contributors for this site, say which does not have the delete rights but all other Contributor rights as is.
Then we need to assign this custom permission level to Contributor group and remove the default ‘Contribute’ permission level from the site.


/// Creating & Assigning custom permission
/// level to Contributor group of root site

/// SpWeb object
/// Group on which the custom permission
/// has to be applied

privatevoid CreateAssignCustomPermissionLevel(SPWeb spWeb, SPGroup myGroup)

spWeb.AllowUnsafeUpdates = true;
//Get the role definition collection for this SPWeb
SPRoleDefinitionCollection sprdcoll = spWeb.RoleDefinitions;
//Define the new custom RoleDefinition
SPRoleDefinition roleDefinition = new SPRoleDefinition();
roleDefinition.Name = “MyCustomRoleDefinition”;
//And then start giving all permisions that you want to give.
roleDefinition.BasePermissions =
| SPBasePermissions.EditListItems
//| SPBasePermissions.DeleteListItems //Delete permission removed from this definition.
| SPBasePermissions.ViewListItems
| SPBasePermissions.OpenItems
| SPBasePermissions.ViewVersions
| SPBasePermissions.DeleteVersions
| SPBasePermissions.CreateAlerts
| SPBasePermissions.ViewFormPages
| SPBasePermissions.BrowseDirectories
| SPBasePermissions.ViewPages
| SPBasePermissions.BrowseUserInfo
| SPBasePermissions.UseRemoteAPIs
| SPBasePermissions.UseClientIntegration
| SPBasePermissions.Open
| SPBasePermissions.EditMyUserInfo;

//Add role definition to spweb

//Assign custom role definition to the contributor group
SPRoleAssignment assignment = new SPRoleAssignment(myGroup);
//Add custom role definition to the SPRoleAssignment
//Add the custom RoleAssignment to the SPWeb.

//Once we have the custom permission level assigned to contributors group,
//we need to remove the default ‘Contribute’ permission level from this web
spWeb.AllowUnsafeUpdates = false;

This method can be placed in feature receiver, where this feature is activated when the site is created on the fly.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s