Assigning New Role Definition to the Group in SharePoint Using REST

In this example you will see how to assign a new role definition to the group in SharePoint using the REST. Develop the project using the following method in the NAPA Tool.

On your Developer Site, open the "Napa" Office 365 Development Tools and then choose Add New Project.

  • Choose the App for SharePoint template, name the project Create Site and then choose the Create button
  • Replace APP.js with the following source code below.
  • Publish Your App


Prerequisites
 
The following is the important procedure to be done before creating the app. Specify the permissions that your app needs as in the following. Choose the Properties button at the bottom of the page.
  • In the Properties window, choose Permissions.
  • In the Content category, set the Write permissions for the Tenant scope.
  • In the Social category, set the Read permissions for the User Profiles scope.
  • Close the Properties window.


The code example in this article sets the custom permissions on a list and then changes a group's permissions to it. The example uses the REST interface to:
  • Get the ID of the target group. The example uses the group ID to get the current role bindings for the group on the list and to add the new role to the list.
  • Get the ID of the role definition that defines the new permissions for the group. The ID is used to add the new role to the list. This example uses an existing role definition for the new role, but you can optionally create a new role definition.
  • Break the role inheritance on the list by using the BreakRoleInheritance method. The example breaks the role inheritance but keeps the current set of roles. (Alternatively, you can choose not to copy any role assignments and to add the current user to the Manage permission level.)
  • Remove the group's current role assignment on the list by sending a DELETE request to the role assignment endpoint. (If you choose not to copy any role assignments, you would skip this step.)
  • Add a role assignment for the group to the list by using the AddRoleAssignment method that binds the group to the role definition and adds the role to the list.
Source Code
  1. 'use strict';  
  2.   
  3. // Change placeholder values before you run this code.  
  4. var listTitle = 'List 1';  
  5. var groupName = 'Group A';  
  6. var targetRoleDefinitionName = 'Contribute';  
  7. var appweburl;  
  8. var hostweburl;  
  9. var executor;  
  10. var groupId;  
  11. var targetRoleDefinitionId;  
  12.   
  13. $(document).ready( function() {  
  14.   
  15.     //Get the URI decoded URLs.  
  16.     hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));  
  17.     appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));  
  18.   
  19.     // Load the cross-domain library file and continue to the custom code.  
  20.     var scriptbase = hostweburl + "/_layouts/15/";  
  21.     $.getScript(scriptbase + "SP.RequestExecutor.js", getTargetGroupId);  
  22. });  
  23.   
  24. // Get the ID of the target group.  
  25. function getTargetGroupId() {  
  26.     executor = new SP.RequestExecutor(appweburl);  
  27.     var endpointUri = appweburl + "/_api/SP.AppContextSite(@target)/web/sitegroups/getbyname('";  
  28.     endpointUri += groupName + "')/id" + "?@target='" + hostweburl + "'";  
  29.   
  30.     executor.executeAsync({  
  31.         url: endpointUri,  
  32.         method: 'GET',  
  33.         headers: { 'accept':'application/json;odata=verbose' },  
  34.         success: function(responseData) {  
  35.             var jsonObject = JSON.parse(responseData.body);  
  36.             groupId = jsonObject.d.Id;  
  37.             getTargetRoleDefinitionId();  
  38.         },  
  39.         error: errorHandler  
  40.    });  
  41. }  
  42.   
  43. // Get the ID of the role definition that defines the permissions  
  44. // you want to assign to the group.  
  45. function getTargetRoleDefinitionId() {  
  46.     var endpointUri = appweburl + "/_api/SP.AppContextSite(@target)/web/roledefinitions/getbyname('";  
  47.     endpointUri += targetRoleDefinitionName + "')/id" + "?@target='" + hostweburl + "'";  
  48.   
  49.     executor.executeAsync({  
  50.         url: endpointUri,  
  51.         method: 'GET',  
  52.         headers: { 'accept':'application/json;odata=verbose' },  
  53.         success: function(responseData) {  
  54.             var jsonObject = JSON.parse(responseData.body)  
  55.             targetRoleDefinitionId = jsonObject.d.Id;  
  56.             breakRoleInheritanceOfList();  
  57.         },  
  58.         error: errorHandler  
  59.     });  
  60. }  
  61.   
  62. // Break role inheritance on the list.  
  63. function breakRoleInheritanceOfList() {  
  64.     var endpointUri = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('";  
  65.     endpointUri += listTitle + "')/breakroleinheritance(true)?@target='" + hostweburl + "'";  
  66.   
  67.     executor.executeAsync({  
  68.         url: endpointUri,  
  69.         method: 'POST',  
  70.         headers: { 'X-RequestDigest':$('#__REQUESTDIGEST').val() },  
  71.         success: deleteCurrentRoleForGroup,  
  72.         error: errorHandler  
  73.     });  
  74. }  
  75.   
  76. // Remove the current role assignment for the group on the list.  
  77. function deleteCurrentRoleForGroup() {  
  78.     var endpointUri = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('";  
  79.     endpointUri += listTitle + "')/roleassignments/getbyprincipalid('" + groupId + "')?@target='" + hostweburl + "'";  
  80.   
  81.     executor.executeAsync({  
  82.         url: endpointUri,  
  83.         method: 'POST',  
  84.         headers: {   
  85.             'X-RequestDigest':$('#__REQUESTDIGEST').val(),  
  86.             'X-HTTP-Method':'DELETE'  
  87.         },  
  88.         success: setNewPermissionsForGroup,  
  89.         error: errorHandler  
  90.     });  
  91. }  
  92.   
  93. // Add the new role assignment for the group on the list.  
  94. function setNewPermissionsForGroup() {  
  95.     var endpointUri = appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('";  
  96.     endpointUri += listTitle + "')/roleassignments/addroleassignment(principalid=" + groupId;  
  97.     endpointUri += ",roledefid=" + targetRoleDefinitionId + ")?@target='" + hostweburl + "'";  
  98.   
  99.     executor.executeAsync({  
  100.         url: endpointUri,  
  101.         method: 'POST',  
  102.         headers: { 'X-RequestDigest':$('#__REQUESTDIGEST').val() },  
  103.         success: successHandler,  
  104.         error: errorHandler  
  105.     });  
  106. }  
  107.   
  108. // Get parameters from the query string.  
  109. // For production purposes you may want to use a library to handle the query string.  
  110. function getQueryStringParameter(paramToRetrieve) {  
  111.     var params = document.URL.split("?")[1].split("&");  
  112.     for (var i = 0; i < params.length; i = i + 1) {  
  113.         var singleParam = params[i].split("=");  
  114.         if (singleParam[0] == paramToRetrieve) return singleParam[1];  
  115.     }  
  116. }  
  117.   
  118. function successHandler() {  
  119.     alert('Request succeeded.');  
  120. }   
  121.   
  122. function errorHandler(xhr, ajaxOptions, thrownError) {  
  123.     alert('Request failed: ' + xhr.status + '\n' + thrownError + '\n' + xhr.responseText);  
  124. }  
Publish

Publish the app and click the Trust it Button.



Output

Request succeeded.