1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Application type API permission with Microsoft Graph API

Discussão em 'Python' iniciado por Stack, Setembro 13, 2024.

  1. Stack

    Stack Membro Participativo


    I want to create an app that will list all my emails in Outlook via Microsoft Graph API.

    What I did:

    1)

    • Go to "Microsoft Entra ID" (former Active Directory)
    • Head to "App registrations" -> "New registration"
    • Select "Accounts in any organizational directory (Any Microsoft Entra ID tenant - Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox)" as Supported Account Type.
    • Create new Client Secret in "Certificates & secrets"
    • In "Authentication" set "Redirect URIs" to "http://localhost:8000"
    • Set up permissions "Mail.Read" and "Mail.ReadBasic" along with the default "User.Read" in "API Permissions". The type of the permissions is Application, not Delegated as I want my app to run in the background without any sign-ups.
    1. My Code:

    import msal
    import requests

    client_id = "my_client_id"
    tenant_id = "my_tenant_id"
    client_secret = "my_client_secret"
    redirect_url = f"http://localhost:8000"

    authority = f"https://login.microsoftonline.com/{tenant_id}/"
    scopes = ["https://graph.microsoft.com/.default"] # This scope means all permissions granted to the app
    app = msal.ConfidentialClientApplication(client_id, client_credential=client_secret, authority=authority)
    result = app.acquire_token_for_client(scopes=scopes)
    #print(result)

    if "access_token" in result:
    access_token = result["access_token"]
    print("Access Token:", access_token)

    # Example of making a request to Microsoft Graph
    headers = {
    "Authorization": f"Bearer {access_token}",
    "Content-Type": "application/json"
    }
    endpoint = "https://graph.microsoft.com/v1.0/users/sriskandaryan3@outlook.com/messages" # Adjust the endpoint as needed
    response = requests.get(endpoint, headers=headers)

    print(f"Error: {response.status_code}, {response.json()}")


    I always get: "Error: the client application 'my_client_id' is missing service principal in the tenant 'SOME TENANT ID (it is interesting that this TENANT ID is NOT my teant_id that I specify in the code)'

    Continue reading...

Compartilhe esta Página