SharePoint recommends assigning role-based permissions. All permissions are managed through roles. Roles are classified into two sections,

Role definition, also known as permission level, is the list of permissions associated with the role. Full control, contribute, read, design, and limited access are some of the role definitions available. Role assignment is the relationship established between users/groups and the role definition. Hence when we assign a role programmatically, it is a two-step process: instantiation of role definition and implementation of role assignment to the user/group.

Let’s see how we can add a role to user/group using JavaScript object model.

Output

Output

Full Code

  1. <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
  2. <script language="javascript" type="text/javascript">
  3. $(document).ready(function()
  4. {
  5. SP.SOD.executeFunc('sp.js', 'SP.ClientContext', addRole);
  6. });
  7. var oSubWebs;
  8. function addRole()
  9. {
  10. //Get client context and web object
  11. var clientContext = new SP.ClientContext();
  12. var oWeb = clientContext.get_web();
  13. //Get the group to be assigned the role
  14. var oGroup = oWeb.get_siteGroups().getByName("HR Group");
  15. //Get Role definition and role definition binding collection
  16. var oRoleDef = oWeb.get_roleDefinitions().getByName('Contribute');
  17. var oBindingColl = SP.RoleDefinitionBindingCollection.newObject(clientContext);
  18. // Add the role to the collection.
  19. oBindingColl.add(oRoleDef);
  20. // Get the RoleAssignmentCollection for the target web.
  21. var oCurrentRoleAssignments = oWeb.get_roleAssignments();
  22. // assign the group to the new RoleDefinitionBindingCollection.
  23. var roleAssignmentContribute = oCurrentRoleAssignments.add(oGroup, oBindingColl);
  24. //Load the client context and execute the batch
  25. clientContext.load(oGroup);
  26. clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
  27. }
  28. function QuerySuccess()
  29. {
  30. console.log("Role definition added Successfully.");
  31. }
  32. function QueryFailure(sender, args)
  33. {
  34. console.log('Request failed - ' + args.get_message());
  35. }
  36. </script>
We can test this in SharePoint by adding it to the Content Editor Web part as below,

Click on Apply. This will add the new role definition to the SharePoint Group. Thus we have seen how to define the role definition and do the role assignment to the group in SharePoint 2016 and SharePoint Online in Office 365 using JavaScript object model.