Setting Permissions Through Code

When working with permissions through the SharePoint API, there are some key objects to take note of.

SPUser – A actual security object in SharePoint (AD User, AD Group or Forms Based User or Group).
SPGroup – A SharePoint group defined through SharePoint.
SPRoleDefinition – A actual role (permission level) defined in SharePoint (Read, Full Control etc…)
SPRoleAssignment – The actual assignment between a SPUser/SPGroup and a SPRoleDefinition


// ******************** Adding a SPUser to a SharePoint Group ********************
// Create the site that contains our list
SPSite oSite = new SPSite("<>");

// Open the web object
SPWeb oWeb = spSite.OpenWeb();

// Get the group that we want to add the user to
SPGroup oGroup = oWeb.Groups["<>"];

// Get the user that we want to add to the group
SPUser oUser = oWeb.AllUsers["domainlogin"];

// Now we add the user to the groups user collection
oGroup.AddUser(oUser);

// Update the group
oGroup.Update();

// ******************** Adding a User to a SharePoint Group ********************
// Create the site that contains our list
SPSite oSite = new SPSite("<>");

// Open the web object
SPWeb oWeb = spSite.OpenWeb();

// Get the group that we want to add the user to
SPGroup oGroup = oWeb.Groups["<>"];

// Now we add the user to the groups user collection
oGroup.AddUser("login", "email", "name", "notes");

// Update the group
oGroup.Update();

Assigning Roles (Permission Levels) to a User or SharePoint Group


// Create the site that contains our list
SPSite oSite = new SPSite("<>");

// Open the web object
SPWeb oWeb = oSite.OpenWeb();

// Get the group that we want to add the user to
SPGroup oGroup = oWeb.Groups["<>"];

// Get the role definition we want to assign ex: Full Control
SPRoleDefinition oRole = oWeb.RoleDefinitions["<< role name>>"];

// Create the role assignment object
SPRoleAssignment oRoleAssignment = new SPRoleAssignment(oGroup);

// Add the role definition to the role assignemnt.
// This will assign the specific permission to the security principal for this role assignemnt.
oRoleAssignment.RoleDefinitionBindings.Add(oRole);

// Now we need to add the role assignment to the web
oWeb.RoleAssignments.Add(oRoleAssignment);

// Now update the web
oWeb.Update();

Enjoy!!..Happy Coding

Comments

Popular posts from this blog

ContextSwitchDeadlock was detected

Architecture is about Intent.. My few cents..