CSOM: Access Denied when loading users from a group

I recently ran into a problem that it was impossible to load users from a SharePoint group using SharePoint Rest API or CSOM.

For authentication an azure AD App with SharePoint API Sites.Read.All Application was used. Every time I tried to load the users of the group (in this case the associated owner group of the site) a 401 Access Denied exception was thrown.

clientContext.Load(clientContext.Web.AssociatedOwnerGroup.Users);
clientContext.ExecuteQuery();

The problem is caused by an inconsistency of the SharePoint APIs. Sites.Read.All is not enough for getting the users of the group if you set a setting in the group called Who can view the membership of the group. When it is set to Group Members your azure ad app needs Sites.FullControl.All instead even though only read operations are executed.

You can check if this problem will occur by checking the OnlyAllowMembersViewMembership setting of the group:


clientContext.Load(clientContext.Web.AssociatedOwnerGroup, g => g.OnlyAllowMembersViewMembership);
clientContext.ExecuteQuery();