Search code examples
c#microsoft-graph-apimicrosoft-graph-sdks

Use a pageIterator with the WithAppOnly() request option


I'm trying to build a .NET8 console app which will do some Microsoft Graph calls using application only permissions. the app uses a certificate to get a token and should authenticate itself without any user prompt.

The code below works as I'm able to set the WithAppOnly option to work only with application permissions :

var devices = await graphServiceClient.DeviceManagement.ManagedDevices.GetAsync(r => r.Options.WithAppOnly());

But if I try to iterate through all pages it seems that the PageIterator ignores the WithAppOnly option and therefore I get the following error :

IDW10502: An MsalUiRequiredException was thrown due to a challenge for the user.

Here's the code I use to iterate :

var devicelist = new List<DeviceModel>();

var pageIterator = PageIterator<ManagedDevice, ManagedDeviceCollectionResponse>.CreatePageIterator(graphServiceClient, devices, (device) =>
{
    devicelist.Add(DeviceModelMapper.MapFromManagedDevice(device));
    return true;
    });
await pageIterator.IterateAsync();

How can I add the withAppOnly request option to the iterator ? Or can I add the WithAppOnly option as default in my graph client ?

And in the worst case how can I iterate through pages without the iterator ?

Thanks !


Solution

  • Have you tried to configure request options for subsequent request?

    var pageIterator = PageIterator<ManagedDevice, ManagedDeviceCollectionResponse>.CreatePageIterator(graphServiceClient, devices, (device) =>
    {
        devicelist.Add(DeviceModelMapper.MapFromManagedDevice(device));
        return true;
    },
    requestInfo=>
    {
        var requestOptions = new List<IRequestOption>();
        requestOptions.WithAppOnly();
        requestInfo.AddRequestOptions(requestOptions);
        return requestInfo;
    });