通过 msgraph-sdk-python-core 在 MS Graph API 中访问 /me
Posted
技术标签:
【中文标题】通过 msgraph-sdk-python-core 在 MS Graph API 中访问 /me【英文标题】:Accessing /me in MS Graph API via msgraph-sdk-python-core 【发布时间】:2022-01-20 14:35:58 【问题描述】:我正在尝试通过 msgraph-sdk-python-core 库访问 MS Graph API 中的 /me
端点。该请求通过 Graph Explorer 工作,但现在我想使用代码。我只是想复制他们在 README.md 中显示的完全相同的请求:
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')
但是,我需要使用非交互式的东西,而不是使用InteractiveBrowserCredential
。 azure-identity 库包含例如 UsernamePasswordCredential
、OnBehalfOfCredential
等,但我不确定应该使用哪个。
我尝试了几种不同的方法,但都导致了不同的错误。根本问题最终可能是 IT 未在 Azure 中正确配置该应用程序。也许他们需要将应用程序激活为“公共客户端”或类似的。但是,在我要求 IT 继续在 Azure 中乱搞之前,我想确认一下我的代码应该是什么样子。
【问题讨论】:
如果回答对您有帮助,请Accept it as an Answer,以便遇到相同问题的其他人可以找到此解决方案并解决他们的问题。 【参考方案1】:如果您在 Azure AD 租户中启用了 MFA,则不能使用 UsernamePasswordCredential
或 OnBehalfOfCredential
,您必须使用 ClientSecretCredential
进行非交互式方法,但不能调用 /me
端点因为您将使用您配置用于调用 Graph API 的 AzureAD 应用程序 进行身份验证,并且您还需要提供 所需的权限在您的应用注册的 API 权限刀片中,与您在 Graph Explorer 中提供的方式相同。
如果您没有启用 MFA,那么您可以使用这两种非交互方法。
ClientSecretCredential:
我正在测试获取所有用户的详细信息,因此我向上述应用提供了Directory.ReadWrite.All
,并使用了以下代码:
from azure.identity import ClientSecretCredential
from msgraph.core import GraphClient
credential = ClientSecretCredential(tenant_id='e186e64a-xxxx-xxxx-xxxx-xxxx',client_secret='L~I7Qxxxxxxxxxxxxxxx',client_id='1be5d8ab-xxxx-xxxx-xxxx-xxxx')
client = GraphClient(credential=credential)
result = client.get('/users')
print(result.json())
输出:
注意:在这个方法/Me
不能被调用,你会得到下面的错误:
由于 Azure 不推荐 UsernamePassowrdCredential,您必须使用 OnbehalfOfCredential。要在 Python 中为 OBO Flow 设置环境,您可以参考此Azure Sample。
或
您可以直接使用 Rest 从 python 调用 Graph API,如下所示:
import requests
import json
tenant_id='e186e64a-xxxxxxxxxxxxxxxxx'
client_secret='L~I7Q~xxxxxxxxxxxxxxxxxxxxxx'
client_id='1be5d8ab-1960-4508-93e4-b138b3295593'
username='admin@xxxxxxxxxxx.onmicrosoft.com'
password='xxxxxxxxxxx'
token_url = 'https://login.microsoftonline.com/<tenant_id>/oauth2/token'
token_data =
'grant_type': 'password',
'client_id': client_id,
'client_secret': client_secret,
'resource': 'https://graph.microsoft.com',
'scope':'https://graph.microsoft.com',
'username':username, #Account with no 2MFA
'password':password,
token_r = requests.post(token_url, data=token_data)
token = token_r.json().get('access_token')
# Use the token using microsoft graph endpoints
users_url = 'https://graph.microsoft.com/v1.0/me'
headers =
'Authorization': 'Bearer '.format(token)
user_response_data = json.loads(requests.get(users_url, headers=headers).text)
print(user_response_data)
输出:
【讨论】:
感谢您的详细解答。我目前对我的计算机的访问权限有限,但最终会尝试您的解决方案并报告! 当然@Salazaja,很高兴能提供帮助:)以上是关于通过 msgraph-sdk-python-core 在 MS Graph API 中访问 /me的主要内容,如果未能解决你的问题,请参考以下文章
如何通过 Windows Azure 通过 GCM 通过唯一 ID 发送特定 Android 设备的通知?