Add user to SharePoint group programmatically (JSOM, CSOM, and Rest API)

In this SharePoint tutorial, we will discuss how to add user to SharePoint group programmatically using JavaScript, CSOM, and Rest API.

We will discuss here the below topics:

  • How to add a user to a SharePoint group using JavaScript
  • How to remove a user from the SharePoint group using JavaScript
  • How to add a user to a SharePoint group using Rest API
  • How to get all users from SharePoint group using Rest API
  • Get all SharePoint groups using JavaScript Object Model (jsom)
  • How to add a user to a SharePoint group using Rest API
  • Get All Users from SharePoint group using Rest API
  • Add Bulk Users to SharePoint Group from Excel using Rest API
  • How to Remove User by login name or User ID from SharePoint Group using Rest API
  • How to create a SharePoint group using Rest API
  • How to update SharePoint group using Rest API
  • Get all users from SharePoint group programmatically using csom
  • Check if user belongs to SharePoint group using CSOM

How to add current user to SharePoint group using JavaScript

This jsom SharePoint tutorial explains, how to add the current SharePoint user to a SharePoint group using the JavaScript object model. We will also see, how to remove the user other than the logged-in user to the SharePoint group using the JavaScript object model (jsom).

Here we will see how to add the logged-in user to the SharePoint group using jsom and also we will see how to add a user (other than the logged-in user) to the SharePoint group using JavaScript in SharePoint Online or SharePoint 2013/2016.

Add user to SharePoint group using JavaScript

Below is the jsom code which we can add inside a script editor web part in a web part page in SharePoint Online/2013/2016.

<input type='button' value='Add User to SharePoint Group' onclick="AddUserToSharePointGroup();"/>
<br />

<script language="javascript" type="text/javascript">
var user;
var spGroup;
function AddUserToSharePointGroup() {

var clientContext = new SP.ClientContext.get_current();

var siteGroups = clientContext.get_web().get_siteGroups();
spGroup=siteGroups.getById(7);
user=clientContext.get_web().get_currentUser();
alert(user.email);
var userCollection=spGroup.get_users();
userCollection.addUser(user);
clientContext.load(user);
clientContext.load(spGroup);
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
}

function onQuerySucceeded() {
alert(‘success');
}

function onQueryFailed() {
alert(‘Request failed.');
}
</script>

Once you run the code, the logged-in user or the current user will be added to the SharePoint group using the JavaScript object model (jsom).

Add user other than logged-in user to SharePoint group using JavaScript object model

Now, we will see how to add a user other than the logged-in user to a SharePoint group using the JavaScript client object model (jsom).

Put the below code inside a script editor web part in a web part page in SharePoint Online or SharePoint 2013/2016.

Here we need to call the ensureUser() method to validate the user. And parameter it will take as domainname\username.

<input type='button' value='Add User to SharePoint Group' onclick="clickMethod();"/>
<br />

<script language="javascript" type="text/javascript">

var user;
var spGroup;
function clickMethod() {

var clientContext = new SP.ClientContext.get_current();

var web=clientContext.get_web();
var siteGroups = clientContext.get_web().get_siteGroups();
spGroup=siteGroups.getById(2544);
//user=clientContext.get_web().get_currentUser();
user=web.ensureUser(“domain\\username");
var userCollection=spGroup.get_users();
userCollection.addUser(user);
clientContext.load(user);
clientContext.load(spGroup);
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);

}

function onQuerySucceeded() {
alert(‘success');
}

function onQueryFailed() {
alert(‘Request failed.');
}
</script>

Remove user from SharePoint group using JavaScript

Similarly, if you want to remove a user from a SharePoint group then we can use the remove() method which usually takes the user as the parameter.

Below is the full code to remove a user from a SharePoint group using JavaScript.

<input type='button' value='Remove User from SharePoint Group' onclick="RemoveUser();"/>
<br />

<script language="javascript" type="text/javascript">

var user;
var spGroup;
function RemoveUser() {

var clientContext = new SP.ClientContext.get_current();
var web=clientContext.get_web();
var siteGroups = clientContext.get_web().get_siteGroups();
spGroup=siteGroups.getById(2544);
//user=clientContext.get_web().get_currentUser();
user=web.ensureUser(“DomainName\\username");
var userCollection=spGroup.get_users();
userCollection.remove(user);
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);

}

function onQuerySucceeded() {
alert(‘success');
}

function onQueryFailed() {
alert(‘Request failed.');
}

</script>

Here we discussed, how to add logged in user as well as other users to SharePoint group using JavaScript object model (jsom) in SharePoint 2013/2016 or SharePoint Online. We will also discuss how to remove a user from a SharePoint group using jsom.

Check if a user belongs to a SharePoint group using JavaScript

Let us see how to check if a user belongs to a SharePoint group or not using the JavaScript client object model (jsom). The jsom code we can use to check if a user belongs to the SharePoint group in SharePoint Online, SharePoint 2016/2013 also.

Below is the full code to check user belongs to SharePoint group using jsom:

function isUserMemberOfSharePointGroup() {
var currentContext = new SP.ClientContext.get_current();
var currentWeb = currentContext.get_web();
var currentUser = currentContext.get_web().get_currentUser();
currentContext.load(currentUser);
var allGroups = currentWeb.get_siteGroups();
currentContext.load(allGroups);
var group = allGroups.getByName('MyTestGroup');
currentContext.load(group);
var groupUsers = group.get_users();
currentContext.load(groupUsers);
currentContext.executeQueryAsync(OnSuccess,OnFailure);
function OnSuccess(sender, args) {
var userInGroup = false;
var groupUserEnumerator = groupUsers.getEnumerator();
while (groupUserEnumerator.moveNext()) {
var groupUser = groupUserEnumerator.get_current();
if (groupUser.get_id() == currentUser.get_id()) {
userInGroup = true;
break;
}
}
alert (userInGroup);
}
function OnFailure(sender, args) {
alert('Something wrong happened !!!');
}
}

Check if user belongs to a SharePoint group JavaScript

Here is another example, how to check if the current logged-in user belongs to a particular SharePoint group using the JavaScript object model.

Here I have a SharePoint group as “Team Site Owners” where I am checking if the current user belongs to the particular group or not.

I have put the below JavaScript code inside a script editor web part in the SharePoint web part page.

<input id="btnCheckUserCurrentGroup" onclick="CheckCurrentUserBelongstoGroup()" type="button" value="Check current user belongs to group" />

<script src="https://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>

<script type="text/javascript">
var userGroups;
function CheckCurrentUserBelongstoGroup()
{
var clientContext = new SP.ClientContext.get_current();
this.currentUser = clientContext.get_web().get_currentUser();
clientContext.load(this.currentUser);
userGroups = this.currentUser.get_groups();
clientContext.load(userGroups);
clientContext.executeQueryAsync(OnQuerySucceeded);

}

function OnQuerySucceeded() {
var isMember = false;
var groupsEnumerator = userGroups.getEnumerator();
while (groupsEnumerator.moveNext()) {
var group= groupsEnumerator.get_current();
if(group.get_title() == "Team Site Owners") {
isMember = true;
break;
}
}
alert(isMember);
}

function OnQueryFailed() {
alert('Error occured');
}

</script>

This is how to check if the user belongs to a SharePoint group javascript object model (jsom) in SharePoint Online/2013/2016.

Get all SharePoint groups using JavaScript Object Model (jsom)

Let us see, how to get all the SharePoint groups on the site using the JavaScript object model in SharePoint 2013/2016 or SharePoint Online.

Below is the code to get all SharePoint groups using jsom (Javascript Object Model) which I can put the below code inside a script editor web part in a page in SharePoint.

<input type='button' value='Get All Groups' onclick="clickMethod();"/>

<br />

<script language="javascript" type="text/javascript">

var siteGroups =";
function clickMethod() {

var clientContext = new SP.ClientContext.get_current();

siteGroups = clientContext.get_web().get_siteGroups();
clientContext.load(siteGroups);
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
}

function onQuerySucceeded() {

var allGroups='Group Name: Group ID ‘+'\n';
for (var i =0 ; i < siteGroups.get_count(); i++)
{
allGroups +=siteGroups.itemAt(i).get_title()+' ‘+siteGroups.itemAt(i).get_id()+'\n';
}
alert(allGroups);
}
function onQueryFailed() {

alert(‘Request failed.');
}
</script>

When you click on the button, it will display all the SharePoint groups and the group id like below:

get all sharepoint groups using jsom
get all sharepoint groups using jsom

This is how to get all SharePoint groups using the JavaScript object model (jsom).

How to add a user to a SharePoint group using Rest API

Now let us see how to add a user to a SharePoint permission group using Rest API. Also, we will see how to get all users from a SharePoint 2013 permission group using the REST API.

Below is the rest api code to add a user to a SharePoint group using rest api. We can put the below Rest API code inside a Script editor web part or content editor web part in a web part page in SharePoint.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<script>
$(function(){
$("#btnClick").click(function(){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups(2544)/users";
$.ajax({
url: requestUri,
type: "POST",
data:JSON.stringify({‘__metadata’: { ‘type’: ‘SP.User’ }, ‘LoginName’: ‘domain\\username’}),
headers: {
"accept":"application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest":$("#_REQUESTDIGEST").val()
},
success: onSuccess,
error: onError
});
function onSuccess(data) {
alert(‘User Added’);
}
function onError(error) {
alert(JSON.stringify(error));
}
});
});
</script>

<input type="button" id="btnClick" value="Add User to SharePoint Group"/>

Get All Users from SharePoint group using Rest API

Here we will see how to get all users from a SharePoint permission group using REST API. We can put the below Rest API code inside a Script editor web part or content editor web part in a web part page in SharePoint.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function(){
$("#btnClick").click(function(){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups(2544)/users";
$.ajax({
url: requestUri,
type: "GET",
headers: {
"accept":"application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest":$("#_REQUESTDIGEST").val()
},
success: onSuccess,
error: onError
});
function onSuccess(data) {
var items = data.d.results;
var results=";
for (var i = 0; i < items.length; i++) {
results+=items[i].LoginName+ " : " + items[i].Email +'\n';
}
alert(results);
}
function onError(error) {
alert(JSON.stringify(error));
}
});
});
</script>

<input type="button" id="btnClick" value="Get All Users From SharePoint Group"/>

Here, we learned, how to add user to SharePoint group using rest api as well as how to retrieve all users from SharePoint group using rest api.

Add Bulk Users to SharePoint Group from Excel using Rest API

Let us see, how to add bulk users to a SharePoint group from Excel using the SharePoint REST API. The same Rest API code, we can use to add bulk users to the SharePoint group.

Recently we have a requirement to add bulk users to a SharePoint group. We have the users in one excel sheet.

In the excel sheet we have only the username like below:

  • bksahoo
  • bijay
  • sahoo like this.

And we have uploaded the excel sheet to the SharePoint SiteAssets library and then we write the code read the excel from SiteAssets library.

Below is the code to add bulk users to SharePoint groups:

<input type=button id="btnClick" value='Click Here' onclick="AddUserFromExcel();" />

<script language="javascript" type="text/javascript">
var i;
var l;
var a1;
var user;
var spGroup;

function AddUserFromExcel()
{
l=1;
var Excel;
Excel = new ActiveXObject(“Excel.Application");
Excel.Visible = false;
for(l=1;l<3;l++)
{
a1=Excel.Workbooks.Open(“http://SiteURL/SiteAssets/Users.xlsx?Web=1").ActiveSheet.Cells(l,1).Value;
var a4="Domain\\"+a1;
var clientContext = new SP.ClientContext.get_current();
var web=clientContext.get_web();
var siteGroups = clientContext.get_web().get_siteGroups();
spGroup=siteGroups.getById(4990);
user=web.ensureUser(a4);
var userCollection=spGroup.get_users();
userCollection.addUser(user);
clientContext.load(user);
clientContext.load(spGroup);
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
function onQuerySucceeded()
{
alert('success');
}
function onQueryFailed()
{
alert('Request failed.');
}
}
}
</script>

This is how to add bulk users to SharePoint group using Rest API.

How to Remove User by login name or User ID from SharePoint Group using Rest API

Let us see, how to remove a user by Login name or user id from a SharePoint security group using Rest API. The rest api code will work in SharePoint 2013 or SharePoint 2016. If you are new to Rest API, check out SharePoint Rest API Tutorial and Examples.

We can easily remove a user from the SharePoint group by login name or by user id using Rest API in SharePoint Online or SharePoint 2013/2016.

You can use removeByLoginName(‘domain\username’) or removed(10) to remove the user from the SharePoint group. Here 10 is the id of the user. Check out this article to know how to get id of the user using Rest Api.

Put the below code inside a script editor web part or content editor web part. This will be a POST Rest API call.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function(){
$("#btnClick").click(function(){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups(2544)/users/removeByLoginName(‘domain\\username’)";
$.ajax({
url: requestUri,
type: "POST",
success: onSuccess,
error: onError
});
function onSuccess(data) {
alert(‘User Removed successfully’);
}
function onError(error) {
alert(JSON.stringify(error));
}
});
});
</script>
<input type="button" id="btnClick" value="Remove User from SharePoint Group"/>

Simillarly, if you want to remove user by id then the rest URL will be like below:

var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups(2544)/users/removebyid(10)";

Here 10 is the id of the user.

This how to remove a user from SharePoint group using rest api by using login name or user id in SharePoint Online/2013/2016.

How to create a SharePoint group using Rest API

Let us see, how to create a group using rest api in SharePoint Online or SharePoint 2013/2016.

Below is the SharePoint rest api code to create a SharePoint group in SharePoint Online or SharePoint 2013/2016 using rest api.

Put the below code inside a script editor web part or content editor web part in a web part page in SharePoint. Once you will click on the button it will create the SharePoint group.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function(){
$("#btnClick").click(function(){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups";
$.ajax({
url: requestUri,
type: "POST",
data:JSON.stringify({'__metadata': { 'type': 'SP.Group' }, 'Title': 'MyTest Group', 'Description':'My Group Description'}),
headers: {
"accept":"application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest":$("#_REQUESTDIGEST").val()
},
success: onSuccess,
error: onError
});
function onSuccess(data) {
alert('Group created successfully');
}
function onError(error) {
alert(JSON.stringify(error));
}
});
});
</script>
<input type="button" id="btnClick" value="Create SharePoint Group"/>

Once you will create on the button, the group will be created like below:

sharepoint rest api create sharepoint group
sharepoint rest api create sharepoint group

How to update SharePoint group using Rest API

Let us see, how to update SharePoint group details using rest api in SharePoint Online/2013/2016.

Below is the rest api code to update SharePoint group details using Rest API in SharePoint 2013/2016 or SharePoint Online. We can add the code inside a script editor or content editor web part in a web part page in SharePoint.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<script>
$(function(){
$("#btnClick").click(function(){
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups(3838)";
$.ajax({
url: requestUri,
type: "POST",
data:JSON.stringify({'__metadata': { 'type': 'SP.Group' }, 'Description':'My New Updated Group Description'}),
headers: {
"content-type": "application/json;odata=verbose",
"X-HTTP-Method":"MERGE"
},
success: onSuccess,
error: onError
});
function onSuccess(data) {
alert('Group description updated successfully');
}
function onError(error) {
alert(JSON.stringify(error));
}
});
});
</script>
<input type="button" id="btnClick" value="Update SharePoint Group Details"/>

This is how to create a SharePoint group using rest api, as well as we saw how to update sharepoint group details using rest api in SharePoint.

Get all users from SharePoint group programmatically using csom

This SharePoint csom tutorial explains, how to get all users from the SharePoint group programmatically using csom (.Net managed object model) code in SharePoint Online.

We have a SharePoint group that has few users in it, the below code will display all the user’s email id in a comma-separated string.

We are doing everything inside a console application. We are trying to connect to a SharePoint online site from the console application. For this, we have stored the Email Address and Password inside the App. Config file.

That information we are retrieving using the below methods.

  • GetSPOAccountName()
  • GetSPOSecureStringPassword()

And then passing as a credentials inside the code.

public static string GetPortalOwnerEmail(string URL)
{
string ownerEmail = string.Empty;
using (ClientContext context = new ClientContext(URL))
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
context.Load(context.Web, w => w.ServerRelativeUrl);
context.Load(context.Web, w => w.Title);
context.ExecuteQuery();
Microsoft.SharePoint.Client.Group group = context.Web.SiteGroups.GetByName(“My Custom SharePoint Group”);

context.Load(context.Web, w => w.Title);
context.Load(group, grp => grp.Title, grp => grp.Users, grp => grp.Owner);
context.ExecuteQuery();
foreach (User usr in group.Users)
{
ownerEmail += usr.Email+”,”;
}

}
return ownerEmail;
}

private static SecureString GetSPOSecureStringPassword()
{
try
{
var secureString = new SecureString();
foreach (char c in ConfigurationManager.AppSettings[“SPOPassword”])
{
secureString.AppendChar(c);
}
return secureString;
}
catch
{
throw;
}
}

private static string GetSPOAccountName()
{
try
{
return ConfigurationManager.AppSettings[“SPOAccount”];
}
catch
{
throw;
}
}

The above SharePoint csom code will give all the users email address as a string separated by comma from a SharePoint group in SharePoint.

Check if user belongs to SharePoint group using CSOM

This SharePoint CSOM tutorial explains, how to check if a particular user belongs to a SharePoint group or not using.Net managed object model code (csom). Here we will pass the email id of the user and the function will return if the user is presented in the group or not.

The code we are writing inside a console application where we have added the SharePoint client object model dlls and we are connecting to a SharePoint Online site.

Below is the full code, the method will take the Site URL, Group name and Email of the user. Here we are retrieving the credentials by using GetSPOAccountName(), GetSPOSecureStringPassword() to connect to SharePoint online site which has been explained in the console application.

public static bool IsUserBelongsToSharePointGroup(string siteURL, string groupName, string email)
{
bool isUserExistInGroup = false;

using (ClientContext context = new ClientContext(siteURL))
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(),GetSPOSecureStringPassword());
context.Load(context.Web, w => w.ServerRelativeUrl);
context.Load(context.Web, w => w.Title, w => w.Url);
context.ExecuteQuery();

Microsoft.SharePoint.Client.Group group = context.Web.SiteGroups.GetByName(groupName);

context.Load(context.Web, w => w.Title);
context.Load(group, grp => grp.Title, grp => grp.Users, grp => grp.Owner);
context.ExecuteQuery();
foreach (User usr in group.Users)
{
if (email == usr.Email)
{
isUserExistInGroup = true;
break;
}
}

}
return isUserExistInGroup;
}

We can call the function like below:

bool isUserBelongsToGroup = IsUserBelongsToSharePointGroup(“https://onlysharepoint2013.sharepoint.com/sites/Bhawana/”, “Bhawana Owners”, “[email protected]”);

Once you run the code it will return if the user belongs to group or not. It will give result like below:

Check if user belongs to SharePoint group using CSOM
Check if user belongs to SharePoint group using CSOM

This is how to check if the user belongs to the SharePoint group using CSOM in SharePoint Online Office 365.

get current user groups sharepoint rest api

Let us see the easy way to get current user group collection through REST API and JQuery in SharePoint 2013/2016/Online. Initially, we have to obtain the current user of the SharePoint group they belong to, which can be achieved using the SharePoint 2013 REST API.

Let’s proceed:
When we use /_api/web/CurrentUser and /_api/web/GetUserById(“+UserID+”)/Groups , we get the current user’s group collection . Right now I am using a workaround that iterates through the (big) result set. To get the group for the current Login User follows the below steps:

Step 1: Navigate to your SharePoint 2013 site.

Step 2: From this page select the Site Actions | Edit Page.

Edit the page, go to the “Insert” tab in the Ribbon, and click the “Web Part” option. In the “Web Parts” dialogue, go to the “Media and Content” category, select the “Script Editor” Web Part and click the “Add button”.

Step 3: Once the Web Part is inserted into the page, you will see an “EDIT SNIPPET” link; click it. You can insert the HTML and/or JavaScript as in the following:

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () { getCurrentUser(); });
function getCurrentUser() {
getUserWebPermissionREST();
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/CurrentUser",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
getCurrentUserGroupColl(data.d.Id);
},
error: function (data) {
failure(data);
}
});
}

function getCurrentUserGroupColl(UserID) {
$.ajax
({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetUserById(" + UserID + ")/Groups",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {

/* get all group’s title of current user. */

var results = data.d.results; var InnrHtmlgrp = "<ul>";
for (var i = 0; i < results.length; i++) {
InnrHtmlgrp += "<li>" + results[i].Title + "</li>";
}
$("#Group").append(InnrHtmlgrp + "</ul>");
}
});
}
</script>
<strong>security Group Name:</strong>
<div id="Group"></div>
get current user group sharepoint rest api
get current user group sharepoint rest api

In the above, you can see the group names on which the current user belongs to.

You may like the following SharePoint Object model tutorials:

In this tutorial, we learned: how to add user to SharePoint group programmatically (JSOM, CSOM and Rest API).

  • How to add the current user to the SharePoint group using JavaScript
  • Add user other than the logged-in user to SharePoint group using JavaScript object model
  • Remove user from SharePoint group using JavaScript
  • Check if a user belongs to a SharePoint group using JavaScript
  • Check if a user belongs to a SharePoint group JavaScript
  • Get all SharePoint groups using the JavaScript Object Model (jsom)
  • How to add a user to a SharePoint group using Rest API
  • Get All Users from SharePoint group using Rest API
  • Add Bulk Users to SharePoint Group from Excel using Rest API
  • How to Remove User by login name or User ID from SharePoint Group using Rest API
  • How to create a SharePoint group using Rest API
  • How to update SharePoint group using Rest API
  • Get all users from SharePoint group programmatically using csom
  • Check if user belongs to SharePoint group using CSOM
>