Search code examples
c#.netasp.net-coremicrosoft-graph-api

Assigning MS Graph API permissions


I'm trying to interrogate the calendar for the logged in user. I can do this using the Graph Explorer fine, but when I try this in code I get an access denied exception. I'm trying to create a system, whereby a user can log-in and then add entries to their calendar, so I assumed a possible way forward would be to programmatically assign permissions; however, this also gives me an error that I don't have permissions. Is someone able to point me in the right direction here; I realise that I can simply allow permission against my own profile, but I need this to be something that any user can simply consent to.

Here's the code that I have to assign permissions:

var requestBody = new CalendarPermission
{
    Role = CalendarRoleType.Read
};

var calendarPermissions = await graphClient.Users[userId].GetAsync();

var result = await graphClient.Users[userId]
    .Calendar.CalendarPermissions["798ee544-9d2d-430c-a058-570e29e34338"]
    .PatchAsync(requestBody);

And here is the code where I try to interrogate the calendar:

var result = await graphClient.Me.Events.GetAsync((requestConfiguration) =>
{
    requestConfiguration.QueryParameters.Select = new[] { "subject", "organizer", "start", "end" };
});

Both return access denied.


Solution

  • I assumed a possible way forward would be to programmatically assign permissions; however, this also gives me an error that I don't have permissions

    Hi, when we want to use graph api, we need to register an Azure AD application in Azure portal, and add required API permissions. Some API permissions are also requiring admin consent.

    In your scenario, you have now having Calendar permission update api and event list api, which both require Calendars.ReadBasic, Calendars.Read, Calendars.ReadWrite api permissions. And like we can see, the permissions are not requiring admin consent.

    enter image description here

    Therefore, before we calling these 2 APIs, we'd better to add API permissions in advance. Just like what we did when testing in Graph Explorer.

    enter image description here

    After adding the API permission, then when you run your app and a user sign in with his account, he would have a popup which indicating a consent is required for using this app.

    enter image description here

    And by my test, even if I didn't add the api permission, I can also add api permission in code to do it.

    builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
        .EnableTokenAcquisitionToCallDownstreamApi(new string[] { "user.read", "Calendars.ReadWrite" })
        .AddInMemoryTokenCaches();
    

    enter image description here