Grant user access to SharePoint site office 365 | Add user to SharePoint site

In this SharePoint tutorial, we will discuss how to grant user access to SharePoint site office 365. We will see step by step, how to add user to SharePoint site.

We will see, how to add user to a SharePoint group programmatically using rest api and csom also.

Once you add a user to a SharePoint site, the user can access the SharePoint site based on the permission you have assigned.

Here, we will see how to grant user access to a SharePoint site in office 365 classic site as well as modern SharePoint site.

As a best practice in SharePoint, we should always add users to a SharePoint group. Never add the users directly on the SharePoint site. It will be difficult to manage the permission for individual users.

So, here we will see, how to add users to a SharePoint group.

Add user to SharePoint site (modern SharePoint site)

Let us see step by step how to add user to the group in Modern SharePoint site.

  • Open your Modern SharePoint site.
  • Click on the gear icon/setting -> Site Permission
Add user to SharePoint site
add user to sharepoint site
  • Click on Invite people and from the drop-down arrow, select add members to group.
  • Under Site Sharing, click on the link Change how members can share, then under Sharing permissions, select the option (Site owner and member can share files, folders and the site. People with edit permission can share files and folders).
  • Left the Rest of the settings by default, and make sure if you have made any changes then click on save.
Add user to SharePoint online site
Invite member to the group of sharepoint site
  • Click on Add member, then enter a name or email address and click on Save.
Add user to the SharePoint site
add members to the group in SharePoint site

And also you can add members directly from the member icon(e.g 1member) in the command bar and click on add member, then enter name or email address and click on Save.

Now you can see one member is added to the group of SharePoint Modern site.

add user to the SharePoint site
Group member in SharePoint group

This is how we can grant user access to SharePoint site in Office 365.

You may like, Create site page in SharePoint online

Grant user access to SharePoint site office 365 (Classic site)

Are you still using the SharePoint Online classic site? Let us see step by step how to grant user access to SharePoint site.

As I said before, we should not add users directly, first you can create a SharePoint group if you do not have.

Follow the below steps to add user to the classic SharePoint site.

  • Open your classic SharePoint site.
  • Click on the gear icon/setting -> Site setting
  • Under User and Permission, click on the people and groups.
how to add users to sharepoint site
how to add users to sharepoint site
  • On the left side, you can see the list of groups, here you can select a group in which you want to add the user, or else you can create a new group with a set of permission levels and add users to the group. To create a customized group, click on the more then click on the dropdown arrow next to the New, click on the New group.
add user to sharepoint group office 365
creating new SharePoint group in SharePoint site
  • Then add group name, description and add group owner.
grant user access to sharepoint site office 365
create a new group for SharePoint classic site
  • Next to the group setting, under ‘who can view the membership of the group?‘, select group member or else if you want everyone can view the membership of the group then select everyone.
  • Under ‘who can edit the membership of the group?’, select group owner, or else you want group member can edit the membership of the group then select group membership.
  • Next to membership request, under ‘Allow request to join the group?’, select no. Otherwise, if you are selecting yes then you send an email to accept the membership.
  • Then we add the permission level i.e the group member of this group having the permission to do action according to the permission. you can choose the permission level according to your requirement.
    1. Full control – has full control
    2. Design – can view, add, update, delete, approve, and customize.
    3. Edit – can add, edit, delete and list; can view, add, update, delete list items and documents.
    4. Contribute – can view, add, update, and delete list items and documents.
    5. Read – can view pages and list items and documents.
    6. Restricted view – can view pages, list items, and documents. Documents can be viewed in the browser but not downloaded.
    7. View only – can view pages, list items, and documents. Documents type with server-side file handlers and can be viewed from the browser but not downloaded.

Note: If your requirement is not satisfied with the default permission level, then you can create a new customized permission level in the SharePoint site-> gear icon-> Site setting-> User and Permission-> Site Permissions-> Permission level-> Add permission level.

And also you can create a new permission level in the SharePoint modern site by following the same steps. According to the permission level, users can use the SharePoint site.

Check out a detailed article on SharePoint permission levels.

  • Click on Create.
allow all users to access sharepoint site
create a group in classic SharePoint site

Now, we can add new user to this newly created group of SharePoint classic site.

Before adding new user make sure that you are in People and Groups -> marketing

  • Click the dropdown next to the New, select Add user.
how to grant user access to sharepoint site
how to grant user access to sharepoint site
  • Next to Invite people, enter the name and email address, and also you can add a personal message.
  • Click on Share.
how to grant user access in sharepoint
adding user to group of SharePoint classic site
  • Now, you can see one more member is added to the group of SharePoint classic site.
how to grant access to sharepoint site
how to grant access to sharepoint site

Note: If you want to create a new group and customized permission level for the SharePoint Modern site. You can create a new group the same as the SharePoint Classic site and the only difference is, how to find the advanced site permissions, therefore for advanced site permissions, open SharePoint Modern site -> Gear icon/settings -> site permission -> Advanced permission settings -> after that you can follow the same step as classic SharePoint site.

Add a user to an existing SharePoint group

In the above steps, we talked about how to create a new group and add users into that group. Now, let us check out how to add a user to an existing SharePoint group.

Open the SharePoint Online site (Classic site) -> click on the gear icon -> then click on the Site Settings.

Then in the Site Settings page click on Site permissions that is under Users and Permissions.

add users to sharepoint site
add users to sharepoint site

Then you can see all the users and groups available like below.

how to add users to sharepoint site
how to add users to sharepoint site

Now to grant user access to the SharePoint site, click on the Grant Permissions button from the ribbon.

Then this will open the Share dialog box. Here fill the below things:

  • Select the user whom you want to grant access to the SharePoint site.
  • Then put a small message if you want to in the message box.
  • Next, click on the show options and there you can see by default the check box “Send an email invitation” will be checked. If you do not want to send an email then uncheck this option.
  • Select a permission level is very important here, by default the Members (Edit) permission will be select. Here, when you click on the dropdown, you can see it will display all the SharePoint groups, and also it will display the individual permission levels. You can see below in the picture.
  • Here, it is always better to choose a SharePoint group, once you choose, the user will be added to the SharePoint group.
  • But if you choose an individual permission level like Full Control, Design, Edir, or Contribute, etc, then the user will be directly added to the SharePoint site which is a very bad practice.
grant user access to sharepoint site office 365
grant user access to sharepoint site office 365

You can see below, I have selected the Contribute access and the user has been added to the SharePoint site directly.

how to grant user access to sharepoint site
how to grant user access to sharepoint site

Imagine, if you will add hundreds of users directly, how difficult it will be to maintain the permission for those users.

Now, let us check out how to add user to SharePoint group programmatically using JSOM, CSOM and Rest API.

Add user to SharePoint group programmatically

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.

In this tutorial, we learned: how to grant users access to sharepoint site office 365.

  • Grant user access to sharepoint site office 365
  • Add user to sharepoint group office 365
  • 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
>