Security Group Operations In SharePoint 2016 Using REST API

SharePoint 2016 general availability had been announced in the Future Of SharePoint conference in May 2016. The series, which discusses the installation of SharePoint 2016 in Azure, can be found at C# Corner from the links, given below:

In this article, we will see how to interact with Security Groups in SharePoint, using REST API. As an initial prerequisite, ensure that the user running the scripts, given below, has Site Collection administrator privileges.

We will use REST to connect to SharePoint to perform the group operations.The scope of the article involves the operations, given below, using REST:

  • Create a new SharePoint Group.
  • Fetch a particular Security Group Properties.
  • Update the Group Properties.
  • Delete an existing security Group.

Create SharePoint Security Group

We can create a SharePoint group by issuing a POST AJAX request. The REST URL endpoint used for the operation is:

/_api/web/sitegroups

We will be creating a key value pair of the information, which will be used to create the Sharepoint group. The group creation information property is shown below. It will send as JSON in the ‘data’ attribute of the AJAX REST call.

  1. var metadata = {  
  2.     '__metadata': {  
  3.         'type''SP.Group'  
  4.     },  
  5.     'Title''Employee Group',  
  6.     'Description''This is a new Employees group'  
  7. }  
Within the _metadata attribute, we have to specify the value for ‘type’, which will specify what object is being created. In our case, it is a group. Hence, we will be specifying ‘SP.Group’.The header section will look like:
  1. headers: {  
  2.     "accept""application/json;odata=verbose",  
  3.     "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
  4.     "content-Type""application/json;odata=verbose"  
  5. },  
Here ‘accept’ attribute specifies the data type for the return value and ‘content-type’ defines the data type for the data required to be sent to the Server. In POST request, we have to send the X-RequestDigest value along with the request for form validation without which we will get a validation error. To fulfil it, we will be assigning the $("#__REQUESTDIGEST"). val() sets the value of the form digest control , present within the page to X-RequestDigest key.

Output

The console output shows a custom successful group creation message, as shown below:

Output

Going to the ‘People and Groups’ page, we can see the newly created group.

People and Groups

Full Code

The full code for the group creation operation is given 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.         var newGroupUrl = "/_api/web/sitegroups";  
  5.         var metadata = {  
  6.             '__metadata': {  
  7.                 'type''SP.Group'  
  8.             },  
  9.             'Title''Employee Group',  
  10.             'Description''This is a new Employees group'  
  11.         }  
  12.         addNewGroup(newGroupUrl, metadata)  
  13.     });  
  14.   
  15.     function addNewGroup(newGroupUrl, metadata) {  
  16.         $.ajax({  
  17.             url: _spPageContextInfo.webAbsoluteUrl + newGroupUrl,  
  18.             type: "POST",  
  19.             headers: {  
  20.                 "accept""application/json;odata=verbose",  
  21.                 "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
  22.                 "content-Type""application/json;odata=verbose"  
  23.             },  
  24.             data: JSON.stringify(metadata),  
  25.             success: function(data) {  
  26.                 console.log(data);  
  27.                 console.log("The group has been created successfully.");  
  28.             },  
  29.             error: function(error) {  
  30.                 alert(JSON.stringify(error));  
  31.             }  
  32.         });  
  33.     }  
  34. </script>  
Retrieve Group Properties

In order to get the property values of the group, we can issue a GET request to the SharePoint Group. The REST URL endpoint is used for AJAXrequest will be of the format :

/_api/web/sitegroups/getbyname('Employee Group')


The method used to send the request will be a GET request. In the headers attribute, we specify the type of return data expected, which is JSON here.The result returned will be parsed in the success call back function.The header of AJAX GET request will be plain and simple, as shown below:
  1. headers: {  
  2.     "accept""application/json;odata=verbose",  
  3. },  
Output

We are trying to retrieve the Group owner property and the value for the property “OnlyAllowMembersViewMembership”, which has come up in the console. Similarly, the other properties can be parsed.

Output

Full Code

The full code for the retrieve operation is given 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.         var newGroupUrl = "/_api/web/sitegroups/getbyname('Employee Group')";  
  5.         retrieveGroup(newGroupUrl)  
  6.     });  
  7.   
  8.     function retrieveGroup(newGroupUrl) {  
  9.         $.ajax({  
  10.             url: _spPageContextInfo.webAbsoluteUrl + newGroupUrl,  
  11.             type: "GET",  
  12.             headers: {  
  13.                 "accept""application/json;odata=verbose",  
  14.             },  
  15.             success: function(data) {  
  16.                 console.log("The group owner is :" + data.d["OwnerTitle"]);  
  17.                 console.log("OnlyAllowMembersViewMembership ? " + data.d["OnlyAllowMembersViewMembership"]);  
  18.             },  
  19.             error: function(error) {  
  20.                 alert(JSON.stringify(error));  
  21.             }  
  22.         });  
  23.     }  
  24. </script>  
Update the Group properties

The Group properties can be updated by issuing AJAX MERGE call, using the REST URL endpoint:
/_api/web/sitegroups/getbyname('Employee Group')

The information to update the group property can be assigned to the metadata key and assigned to ‘data’ attribute of the AJAX call.
  1. var metadata = {  
  2.         __metadata: {  
  3.             'type': SP.Group '},  
  4.             OnlyAllowMembersViewMembership: false  
  5.         };  
Here, we are updating the “OnlyAllowMembersViewMembership” property of the group to ‘False’, which was earlier ‘True’. The header section looks similar to the previous operations.
  1. headers: {  
  2.     "accept""application/json;odata=verbose",  
  3.     "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
  4.     "content-Type""application/json;odata=verbose",  
  5. },  
Output

Thus, the successful group updating message has come up in the console.

Output

Going to the group settings page, the property value for “OnlyAllowMembersViewMembership” has been changed from “Group Members” to “Everyone”, based on the script.

Group Members

Full Code

The full code for the update operation is given 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.         var newGroupUrl = "/_api/web/sitegroups/getbyname('Employee Group')";  
  5.         var metadata = {  
  6.             __metadata: {  
  7.                 'type''SP.Group'  
  8.             },  
  9.             OnlyAllowMembersViewMembership: false  
  10.         };  
  11.         updateGroup(newGroupUrl, metadata)  
  12.     });  
  13.   
  14.     function updateGroup(newGroupUrl, metadata) {  
  15.         $.ajax({  
  16.             url: _spPageContextInfo.webAbsoluteUrl + newGroupUrl,  
  17.             type: "MERGE",  
  18.             data: JSON.stringify(metadata),  
  19.             headers: {  
  20.                 "accept""application/json;odata=verbose",  
  21.                 "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
  22.                 "content-Type""application/json;odata=verbose",  
  23.             },  
  24.             success: function(data) {  
  25.                 console.log(data);  
  26.                 console.log("Group membership property has been updated.");  
  27.             },  
  28.             error: function(error) {  
  29.                 alert(JSON.stringify(error));  
  30.             }  
  31.         });  
  32.     }  
  33. </script>  
Delete the SharePoint Security Group

In order to delete the SharePoint group, we cannot issue an AJAX DELETE request. Instead, we will make use of the below REST Endpoint and issue a POST request. If we issue a DELETE AJAX request, we will get an error message stating that “Delete” call is not supported with the Groups.

/_api/web/sitegroups/removebyloginname('Employee Group’)


‘RemoveByLoginName’ specifies the name of the group to be deleted. In the header section, we can specify the ‘accept’ and ‘X-RequestDigest’ attribute, which specifies the return data type and the form digest value respectively. The “IF-Match” attribute is used to check concurrency of the group to ensure that the group that is being deleted is really the one, that we intend to delete. We can either specify “*”, which will blindly skip the concurrency check, else we can specify the e-tag value (which can be obtained by issuing a GET request).

Output

On running the script for the group deletion, a success message has come up in the console, as shown below:

Output

Full Code

The full code for the delete operation is given 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.         var existingGroupUrl = "/_api/web/sitegroups/removebyloginname('Employee Group')";  
  5.         deleteGroup(existingGroupUrl)  
  6.     });  
  7.   
  8.     function deleteGroup(existingGroupUrl) {  
  9.         $.ajax({  
  10.             url: _spPageContextInfo.webAbsoluteUrl + existingGroupUrl,  
  11.             type: "POST",  
  12.             headers: {  
  13.                 "accept""application/json;odata=verbose",  
  14.                 "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
  15.                 "IF-MATCH""*"  
  16.             },  
  17.             success: function(data) {  
  18.                 console.log("The group has been successfully deleted.");  
  19.             },  
  20.             error: function(error) {  
  21.                 alert(JSON.stringify(error));  
  22.             }  
  23.         });  
  24.     }  
  25. </script>  
Let’s see how to implement the scripts, shown above, in SharePoint. The steps, given below, will demo, how to add the script for deleting the group. Similarly other scripts can also be tested. Save the script as a text file and upload it to the site assets library.

SharePoint Implementation 
  • Go to the edit settings of SharePoint page and click Web part from the Insert tab

     edit settings

  • Add Content Editor Web part.

    Web part

  • Click Edit Web art from Content Edit Web part. Assign the URL of the script text file and click Apply.

    Content Edit Web part

  • Click Apply and we can see the successful list deletion message from the console.

I had the group settings page opened in the Browser, prior to running the script. Refreshing it gives the error, shown below, stating the removal of the group.

error

Summary

Thus, we have seen how to create a SharePoint Security group, retrieve its properties, update the group properties and finally delete the existing group, using REST API in SharePoint 2016.This will work the same way in Office 365 as well.