Error while adding event using Microsoft graph api

140 Views Asked by At

I am trying to add calendar event using Microsoft graph API in python. However I am getting

{'error': {'code': 'ErrorInvalidUser', 'message': "The requested user '[email protected]' is invalid."}}

Below is the code I am using:

def get_access_token(tenant_id, client_id, client_secret):
    url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
    headers = {
        "Content-Type": "application/x-www-form-urlencoded",
    }
    data = {
        "grant_type": "client_credentials",
        "client_id": client_id,
        "client_secret": client_secret,
        "scope": "https://graph.microsoft.com/.default",
    }
    response = requests.post(url, headers=headers, data=data)
    access_token = response.json().get("access_token")
    return access_token


def create_event(access_token, user_id):
    url = f"https://graph.microsoft.com/v1.0/users/{user_id}/events"
    headers = {
        "Authorization": f"Bearer {access_token}",
        "Content-Type": "application/json",
    }
    data = {
        "subject": f"{event_date['Event']}",
        "start": {
            "dateTime": f"{event_date['Date']}",
            "timeZone": "Indian Standard Time",
         },
        "end": {
            "dateTime": f"{event_date['Date']}",
            "timeZone": "Indian Standard Time",
        },
    }
    response = requests.post(url, headers=headers, json=data)
    print(response.json())

I have registered my application in Azure Entra ID (Active Directory). Allowed below API permissions:

enter image description here

My account is registered in Azure Active Directory as Guest user type. I have also assigned the application to this user ID.

Is there anything I am missing? Please let me know. Thank you

1

There are 1 best solutions below

1
On

You are using client credentials flow which requires application permissions, not delegated.

Try to add application permission Calendars.ReadWrite. Delegated permissions can be removed.

Additionally, check this article. There can be a company policy that blocks access to some (or all) mailboxes and requires to create a new ApplicationAccessPolicy to be able to access/modify those mailboxes.