I am testing the new "Sites.Selected" Permission in MS Graph and wanted to combine it with managed Identity to connect to SharePoint Online. I've read on some blogs that the new permission won't work with CSOM so my idea was to create an Azure Function, Enable Managed Identity, assign the 'Sites.Selected' Role and simply read the Title of the Web using MS Graph but I'm getting access denied errors.
What did I do?
- Create an Azure Function Solution with the following code
var azureServiceTokenProvider = new AzureServiceTokenProvider();
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://graph.microsoft.com/");
log.LogInformation(accessToken);
var graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider((requestMessage) =>
{
requestMessage
.Headers
.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
return Task.CompletedTask;
}));
log.LogInformation("Authenticated");
var site = await graphClient.Sites["GUID-OF-MY-SITE"]
.Request()
.GetAsync();
- Enabled Managed Identity in Azure Portal manually via settings
- Assigned 'Sites.Selected' role using AzureAD PowerShell
$msi = Get-AzureADServicePrincipal -SearchString "SharePointGate"
$graph = Get-AzureADServicePrincipal -Filter "AppId eq '00000003-0000-0000-c000-000000000000'"
$urp = $graph.AppRoles | where Value -Like "Sites.Selected" | Select-Object -First 1
New-AzureADServiceAppRoleAssignment `
-Id $urp.Id `
-ObjectId $msi.ObjectId `
-PrincipalId $msi.ObjectId `
-ResourceId $graph.ObjectId
At this point I can confirm the role has been added by checking with Get-AzureADServiceAppRoleAssignedTo
- Add the AppId to the SiteCollection
Grant-PnPAzureADAppSitePermission -AppId $msi.ObjectId -DisplayName 'SharePointGate' -Site 'https://mydevspo.sharepoint.com/sites/testsite' -Permissions Write
- Test the Function in azure portal, where I receive Access Denied.
If I review the token from the log I can see the correct AppId and Role:

- If I also add "Sites.FullControl.All" like I do in step (3) it starts working
In theory it should also work without step 6, right? What am I missing?