Sohryu
Sohryu

Reputation: 63

Connect to SharePoint via Graph, Sites.Selected and Managed Identity

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?

  1. 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();
  1. Enabled Managed Identity in Azure Portal manually via settings
  2. 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

  1. Add the AppId to the SiteCollection
Grant-PnPAzureADAppSitePermission -AppId $msi.ObjectId -DisplayName 'SharePointGate' -Site 'https://mydevspo.sharepoint.com/sites/testsite' -Permissions Write
  1. 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: enter image description here
  1. 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?

Upvotes: 2

Views: 1414

Answers (1)

Joy Wang
Joy Wang

Reputation: 42133

You gave the Write permission in the Grant-PnPAzureADAppSitePermission command, but your code did a get operation, try to use Read instead in this command.

Grant-PnPAzureADAppSitePermission -AppId $msi.ObjectId -DisplayName 'SharePointGate' -Site 'https://mydevspo.sharepoint.com/sites/testsite' -Permissions Read

Upvotes: 0

Related Questions