如何在msgraph.GraphServiceClient上进行身份验证?

问题描述 投票:0回答:1

没有任何文档可以做到这一点,我发现这是不可接受的。

from msal import ConfidentialClientApplication
from msgraph import GraphServiceClient

client_id = ''
client_secret = ''
tenant_id = ''
authority = f'https://login.microsoftonline.com/{tenant_id}'
scopes = ['https://graph.microsoft.com/.default']

app = ConfidentialClientApplication(
    client_id,
    authority=authority,
    client_credential=client_secret,
)

response = app.acquire_token_for_client(scopes)

graph_client = GraphServiceClient(
    credentials=response,
    scopes=scopes
)


await graph_client.users.get()

get_authorization_token 中的/usr/local/lib/python3.10/dist-packages/kiota_authentication_azure/azure_identity_access_token_provider.py(self,uri,additional_authentication_context) 101) 102 其他: --> 103 结果 = self._credentials.get_token(*self._scopes, Claims=decoded_claim) 104 105 if检查.iswaitable(结果): AttributeError:“dict”对象没有属性“get_token”

分析堆栈,您可以看到在

msgraph
客户端中作为凭据传递的对象不是它所期望的;
acquire_token_for_client
返回一个字典,但
GraphServiceClient
期望它有一个名为“get_token”的函数。

如何解决这个问题?

python azure microsoft-graph-api office365
1个回答
0
投票

我注册了一份 Entra ID 申请并授予了

User.Read.All
Application 类型的权限,如下所示:

enter image description here

最初,当我运行您的代码来获取这样的用户列表时,我也遇到了同样的错误

from msal import ConfidentialClientApplication
from msgraph import GraphServiceClient

client_id = ''
client_secret = ''
tenant_id = ''
authority = f'https://login.microsoftonline.com/{tenant_id}'
scopes = ['https://graph.microsoft.com/.default']

app = ConfidentialClientApplication(
    client_id,
    authority=authority,
    client_credential=client_secret,
)

response = app.acquire_token_for_client(scopes)

graph_client = GraphServiceClient(
    credentials=response,
    scopes=scopes
)


result = await graph_client.users.get()
print(result)

回复:

enter image description here

要解决该错误,请使用以下修改的代码,该代码使用客户端凭据流对 MS Graph 进行身份验证并成功列出用户:

import asyncio
from azure.identity import ClientSecretCredential
from msgraph import GraphServiceClient

tenant_id = "tenantID"
client_id = "appID"
client_secret = "secret"

credential = ClientSecretCredential(
    tenant_id=tenant_id,
    client_id=client_id,
    client_secret=client_secret
)

client = GraphServiceClient(credential)

async def main():
    result = await client.users.get()
    users = result.value

    for user in users:
        print("User ID:", user.id)
        print("User Display Name:", user.display_name)
        print("-" * 50)  # Separating each user with a line

asyncio.run(main())

回复:

enter image description here

参考资料:

列出用户 - Microsoft Graph

GitHub - microsoftgraph/msgraph-sdk-python

© www.soinside.com 2019 - 2024. All rights reserved.