title: Connect to SharePoint via Graph, Sites.Selected and Managed Identity
body: <p>I am testing the new &quot;Sites.Selected&quot; 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.</p>
  <p>What did I do?</p>
  <ol>
  <li>Create an Azure Function Solution with the following code</li>
  </ol>
  <pre><code>var azureServiceTokenProvider = new AzureServiceTokenProvider();
  string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync(&quot;https://graph.microsoft.com/&quot;);
  log.LogInformation(accessToken);
  var graphClient = new GraphServiceClient(
  new DelegateAuthenticationProvider((requestMessage) =&gt;
  {
   requestMessage
   .Headers
   .Authorization = new AuthenticationHeaderValue(&quot;bearer&quot;, accessToken);
       return Task.CompletedTask;
  }));
  log.LogInformation(&quot;Authenticated&quot;);
   
  var site = await graphClient.Sites[&quot;GUID-OF-MY-SITE&quot;]
  .Request()
  .GetAsync();
  </code></pre>
  <ol start="2">
  <li>Enabled Managed Identity in Azure Portal manually via settings</li>
  <li>Assigned 'Sites.Selected' role using AzureAD PowerShell</li>
  </ol>
  <pre><code>$msi = Get-AzureADServicePrincipal -SearchString &quot;SharePointGate&quot;
  $graph = Get-AzureADServicePrincipal -Filter &quot;AppId eq '00000003-0000-0000-c000-000000000000'&quot;
  $urp = $graph.AppRoles | where Value -Like &quot;Sites.Selected&quot; | Select-Object -First 1
  New-AzureADServiceAppRoleAssignment `
               -Id $urp.Id `
               -ObjectId $msi.ObjectId `
               -PrincipalId $msi.ObjectId `
               -ResourceId $graph.ObjectId
  </code></pre>
  <p>At this point I can confirm the role has been added by checking with Get-AzureADServiceAppRoleAssignedTo</p>
  <ol start="4">
  <li>Add the AppId to the SiteCollection</li>
  </ol>
  <pre><code>Grant-PnPAzureADAppSitePermission -AppId $msi.ObjectId -DisplayName 'SharePointGate' -Site 'https://mydevspo.sharepoint.com/sites/testsite' -Permissions Write
  </code></pre>
  <ol start="5">
  <li>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:
  <a href="https://i.stack.imgur.com/Ja70B.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ja70B.png" alt="enter image description here" /></a></li>
  </ol>
  <ol start="6">
  <li>If I also add &quot;Sites.FullControl.All&quot; like I do in step (3) it starts working</li>
  </ol>
  <p>In theory it should also work without step 6, right? What am I missing?</p>