We are using REST (with jQuery ajax) to create groups and add members to the groups. We are using the code below (cleaned up a little for legibility).
function createGroup(title,user){
var payload = {'__metadata':{ 'type':'SP.Group'},
'Title':title,
};
var obj = { url: webUrl + '/_api/web/sitegroups',
type: "POST",
headers: headers,
data: JSON.stringify(payload)
};
return $.ajax(obj)
.then(function(data){
var groupId = data.d.Id;
// add a user to the new group
var payload={ '__metadata':{'type':'SP.User'},
'LoginName':user
};
var obj = { url: webUrl + "/_api/web/SiteGroups("+groupId+")/Users",
type:"POST",
data:JSON.stringify(payload),
headers:headers
};
return $.ajax(obj);
})
.then(function(){
// more code here for more stuff
});
}
The first part of the call creates a new group and the id of that group is returned. That part works great.
In the .then()
we use the newly created group's id and add a user to that group. The code works great if the person running it is a site collection owner.
If the person running the code is not a site collection owner (but does have Full Control) we get an interesting result. We don't want to make everyone site collection admins!
Using our debug tools and watching the XHR in the browser debugger we see:
- Call create the group and return its id
- call to
.../Users
endpoint to add user - SP opens an authentication challenge window. While the window is open, the network debugger shows the call as pending.
- Can't authenticate so click cancel.
- Network shows 401 unauthorized and the rest of the code doesn't execute
The strange part is the user is actually added to the group at step 2. As soon as the call is made, but still pending we can go through the UI and see the group and that the user is in the group.
First big question
If the REST call is cancelled or unauthorized, how/why is the user getting added to the group?
First additional mystery is that if the person running the code adds themselves to the group the above issue doesn't happen. Everything works smoothly and as expected.
Second additional mystery is that the code we are using we have been using elsewhere. We checked it there -- evidently it has always been run by a site collection admin before. In that case (when we removed collection admin) we almost the same result
- the group was created and returned its id
- .../Users endpoint called
- authentication window pops up
- authentication window closes itself (strange!)
- network call shows cancelled
- the rest of the code executes
In the end everything works and the user gets added to new group even though the call to /Users endpoint shows cancelled in network log. The two sites are on different site collections, but we can't find any reason why it behaves differently.
Second big question
If we can't get rid of the authentication window popping up any ideas on where to look for the magic auto-cancelling-without-breaking-the-rest-of-the-code authentication request?