Security management is a prime concern in SharePoint, as the right content has to be served to the right people with the adequate permissions. SharePoint recommends assigning role-based permissions. All the permissions are managed through the roles. Roles are classified into two sections:

Role definition, also known as a 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 the role definition and an implementation of the role assignment to the user/group. You can check out, how to create a new role definition in this article.

Through this article, let’s see how we can add a role to user using JavaScript object model.

Internal Implementation

Full Code: The full code to update the role definition is shown below:

  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. SP.SOD.executeFunc('sp.js', 'SP.ClientContext', addRoleToUser);
  5. });
  6. function addRoleToUser() {
  7. //Get client context and web object
  8. var clientContext = new SP.ClientContext.get_current();
  9. var oWeb = clientContext.get_web();
  10. //Get current user and role definition object
  11. var oUser = oWeb.get_currentUser();
  12. var roleDef = oWeb.get_roleDefinitions().getByName("Custom Role Definition");
  13. var collRoleDefinitionBinding = SP.RoleDefinitionBindingCollection.newObject(clientContext);
  14. //Add the role definition to the user's role definition collection
  15. collRoleDefinitionBinding.add(roleDef);
  16. oWeb.get_roleAssignments().add(oUser, collRoleDefinitionBinding);
  17. //Execute the batch
  18. clientContext.executeQueryAsync(Succeeded, Failure);
  19. }
  20. function Succeeded() {
  21. console.log('The role definition has been added to the user.');
  22. }
  23. function Failure(sender, args) {
  24. console.log('Request failed' + args.get_message());
  25. }
  26. </script>
We can test this in SharePoint by adding it to the Content Editor Web part as below,

SharePoint Implementation

Output: Before running JSOM code in the client side Browser, the screen will look, as shown below:

Output

After running JSOM code in the client side browser, Custom Role Definition has been added to the user.

Output

Summary

Thus, we have seen, how to add the new role definition to SharePoint Users. This has been tested in both SharePoint 2016 and Office 365.