Receiving accessDenied when using App Only permissions calling Graph API sites?search=*

419 Views Asked by At

I have a web application which uses App only tokens to override the end user's permission to retrieve all Site Collections in the tenant. When attempting to use the boiler plate code provided in the example with one minor change, the Graph API is returning accessDenied when attempting to issue the call https://graph.microsoft.com/v1.0/sites?search=*. If I remove WithAppOnly(), the call succeeds [if Delegated rights for Sites.Read.All is assigned]. The Azure AD registered app has admin approved Application-scoped Sites.Read.All assigned to it.

            var queryOptions = new List<QueryOption>()
            {
                new QueryOption("search","*")
            };

            var sites = await graphServiceClient.Sites.Request(queryOptions)
                .WithAppOnly()
                .WithScopes("Sites.Read.All")
                .GetAsync();
ServiceException: Code: accessDenied
Message: Access denied
Inner error:
AdditionalData:
date: 2021-03-20T21:45:27
request-id: 16933bd6-5e7f-4820-9563-fec75575c9b2
client-request-id: 16933bd6-5e7f-4820-9563-fec75575c9b2
ClientRequestId: 16933bd6-5e7f-4820-9563-fec75575c9b2
1

There are 1 best solutions below

3
unknown On

You need to add Sites.Read.All of applicaiton permission in the Azure portal. enter image description here

Note: Click the enter image description here, because this permission is admin consent required.

Try to test with client credentials flow.

// Get access token
POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded

client_id={client_id}
&scope=https://graph.microsoft.com/.default
&client_secret={client_secret}
&grant_type=client_credentials

// Call MS Graph API
GET https://graph.microsoft.com/v1.0/sites?search={query}