将 Microsoft Graph Core Python 客户端库与 Azure Active Directory 应用程序注册(客户端 ID 和密码)一起使用

Use Microsoft Graph Core Python Client Library with the Azure Active Directory App registration (client id & secret)

Microsoft Graph Core Python Client Library 的文档和示例仅显示了 InteractiveBrowserCredential 的用法。

# python -m pip install msgraph-core
# python -m pip install azure-identity

from azure.identity import InteractiveBrowserCredential
from msgraph.core import GraphClient

browser_credential = InteractiveBrowserCredential(client_id='YOUR_CLIENT_ID')
client = GraphClient(credential=browser_credential)
result = client.get('/me')
print(result.json())

如何通过提供Azure Active Directory App注册的cleint idsecret而无需交互就可以使用GraphClient

使用以下 URL 配置您的 Azure Active Directory 应用程序注册:
https://docs.microsoft.com/en-us/graph/auth-v2-service

Python 库 "Azure Identity client library for Python (azure-identity)" 提供了多种身份验证选项。
"Authenticate service principals" 无需任何交互即可实现与 Azure Active Directory 应用程序注册的身份验证。

# python -m pip install msgraph-core
# python -m pip install azure-identity

from azure.identity import ClientSecretCredential
from msgraph.core import GraphClient

client_secret_credential = ClientSecretCredential(
    tenant_id='XXX',
    client_id='XXX',
    client_secret='XXX')

client = GraphClient(credential=client_secret_credential)

result = client.get(
    '/groups',
    params={
        '$select': 'displayName',
        '$top': '10'
    },
)
pprint(result.json())