要在代码中使用包含 MSGraph 的 MSAL,您需要按照以下步骤进行操作:
from msal import PublicClientApplication
import requests
client_id = 'YOUR_CLIENT_ID'
tenant_id = 'YOUR_TENANT_ID'
authority = f'https://login.microsoftonline.com/{tenant_id}'
app = PublicClientApplication(client_id, authority=authority)
scopes = ['User.Read'] # 授予用户读取权限的范围
result = None
accounts = app.get_accounts()
if accounts:
result = app.acquire_token_silent(scopes, account=accounts[0])
if not result:
result = app.acquire_token_interactive(scopes)
access_token = result['access_token']
graph_api_endpoint = 'https://graph.microsoft.com/v1.0/me'
headers = {'Authorization': 'Bearer ' + access_token}
response = requests.get(graph_api_endpoint, headers=headers)
if response.status_code == 200:
data = response.json()
# 在这里处理返回的数据
else:
print('请求失败:', response.status_code, response.text)
在上述代码示例中,您需要将 YOUR_CLIENT_ID
和 YOUR_TENANT_ID
替换为您应用程序的实际值。此外,您还可以根据需要修改所需的范围和 Graph API 端点。
请注意,这只是一个简单的示例,用于演示如何使用包含 MSGraph 的 MSAL 进行身份验证和调用 MS Graph API。您可能需要根据您的具体需求进行进一步的定制和错误处理。