azureoutlookmicrosoft-graph-api

Microsoft Graph APi users/{email}/messages error: Access is denied. Check credentials and try again


Our org. has an email they made in outlook mail. I'm able to use the Microsoft Graph API using the endpoint me/messages but now I wanted to run this in python (in an azure databricks notebook). So I created a new App in azure portal for this and the only steps I've done otherwise is adding delegated permissions and saving the clientid, secret id, tenant id from there. I have the below code which throws the error:'Access is denied. Check credentials and try again.' Also, I'm able to get a token..

I've added the following delegated permissions...

email ,Mail.Read ,Mail.ReadWrite, User.Read

And this code:

authority = f"https://login.microsoftonline.com/{tenant_id}"
scope = ["https://graph.microsoft.com/.default"]
# scope = ["https://graph.microsoft.com/Mail.Read"]


app = msal.ConfidentialClientApplication(
    client_id,
    authority=authority,
    client_credential=secret_value
)


result = None
result = app.acquire_token_silent(scope, account=None)

if not result:
    print("No suitable token exists in cache. Requesting a new one...")
    result = app.acquire_token_for_client(scopes=scope)

if "access_token" in result:
    print('using access token...')

    headers = {'Authorization': 'Bearer ' + result['access_token']}
    graph_endpoint = f'https://graph.microsoft.com/v1.0/users/{email}/messages'
    response = requests.get(graph_endpoint, headers=headers)

    if response.status_code == 200:
        emails = response.json()
        print(emails)
    else:
        print(f"Error fetching emails: {response.status_code}")
        print(response.json()) 
else:
    print(f"Error acquiring token: {result.get('error')}, {result.get('error_description')}")

Solution

  • The error occurred as you granted permissions of Delegated type which won't work with client credentials flow.

    Initially, I too got same error when I ran the code by granting permissions of Delegated type:

    enter image description here

    To resolve the error, make sure to add Mail.Read permission of Application type by granting admin consent as below:

    enter image description here

    When I ran the code again after granting permissions of Application type, I got the response successfully like this:

    import json
    import msal
    import requests
    
    tenant_id = "tenantId"
    client_id = "appId"
    secret_value = "secret"
    email = "sri@xxxxxxxxx.onmicrosoft.com"
    authority = f"https://login.microsoftonline.com/{tenant_id}"
    scope = ["https://graph.microsoft.com/.default"]
    
    app = msal.ConfidentialClientApplication(
        client_id,
        authority=authority,
        client_credential=secret_value
    )
    
    result = app.acquire_token_silent(scope, account=None)
    
    if not result:
        print("No suitable token exists in cache. Requesting a new one...")
        result = app.acquire_token_for_client(scopes=scope)
    
    if "access_token" in result:
        print('Using access token...')
    
        headers = {'Authorization': 'Bearer ' + result['access_token']}
        graph_endpoint = f'https://graph.microsoft.com/v1.0/users/{email}/messages'
        response = requests.get(graph_endpoint, headers=headers)
    
        if response.status_code == 200:
            emails = response.json()
            print(json.dumps(emails, indent=4))
        else:
            print(f"Error fetching emails: {response.status_code}")
            print(response.json()) 
    else:
        print(f"Error acquiring token: {result.get('error')}, {result.get('error_description')}")
    

    Response:

    enter image description here