You could use the following REST query to retrieve AD groups (SecurityGroup type: 4
):
/_api/web/siteusers?$filter=PrincipalType eq 4
How to add AD Group into SP Group using SharePoint REST Interface
The following example demonstrates how to add AD Group named DOMAIN\Intranet-Owners
into SharePoint Owners
Group using JavaScript:
The solution consists of:
- Request AD Group by Title - see method
getUserByTitle
(the only purpose of this step is to retrieve SP.User
details by Title
, in particular LoginName
)
- Add AD Group into SP Group - see method
insertUserToGroup
. Note: AD Group is added into SP Group as SP.User
entity
Example:
function createJson(url,payload)
{
return $.ajax({
url: url,
type: "POST",
data: JSON.stringify(payload),
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest" : $("#__REQUESTDIGEST").val()
}
});
}
function getJson(url)
{
return $.ajax({
url: url,
type: "GET",
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose"
}
});
}
function insertUserToGroup(webUrl, userTitle,groupId)
{
return getUserByTitle(webUrl,userTitle).then(function(data){
var usersEndpointUrl = webUrl + "/_api/web/sitegroups(" + groupId + ")/users";
if(data.d.results.length == 1) {
var user = data.d.results[0];
var usersPayload = { '__metadata': { 'type': 'SP.User' }, 'LoginName': user.LoginName };
return createJson(usersEndpointUrl,usersPayload);
}
});
}
function getUserByTitle(webUrl,title){
var userEnpointUrl = webUrl + "/_api/web/siteusers?$filter=Title eq '" + title + "'";
return getJson(userEnpointUrl);
}
var ownersGroupId = 6;
var adGroupName = "DOMAIN\Intranet-Owners";
insertUserToGroup(_spPageContextInfo.webAbsoluteUrl,adGroupName,ownersGroupId)
.done(function()
{
console.log('User has been added');
})
.fail(
function(error){
console.log(JSON.stringify(error));
});
NOTE:
You may need to use the ensureUser webmethod instead of the siteUsers one, in case you notice that you are not getting results for the target user.