我正在尝试将对 Graph API 的使用从通过
requests
执行 http 请求迁移到使用 Python SDK。我使用的是 acquire_token_by_username_password
方法,请求处理正确。当迁移到使用 Python SDK 时,我正在创建我的客户端,如下所示:
credential = UsernamePasswordCredential(
client_id=self._client_id,
username=username,
password=password,
)
return GraphServiceClient(credential, self._scopes)
然后尝试发出如下请求:
await client.users.get(request_configuration=request_configuration)
但是,使用与我在 HTTP 方法中使用的相同的凭据,我得到:
APIError
Code: 403
message: None
error: MainError(additional_data={}, code='Authorization_RequestDenied', details=None, inner_error=InnerError(additional_data={}, client_request_id='53e56211-cd3d-47d5-b3fb-b6dacd6088a8', date=DateTime(2024, 2, 25, 11, 10, 15, tzinfo=Timezone('UTC')), odata_type=None, request_id='4b92be4e-d60a-4040-bcb4-e8d11a636879'), message='Insufficient privileges to complete the operation.', target=None)
我已尝试重新同意 azure 中的(委派)权限;不知道我还能做什么。
如果用户或服务主体没有执行操作所需的权限或角色,通常会发生错误。
最初,当我在不足以列出用户的范围中通过User.Read
时,我也遇到了同样的错误:
要解决错误,您需要通过授予管理员同意,在应用程序注册中至少添加User.Read.All委派权限:
当我通过将 scope 值更改为 User.Read.All 来运行下面修改后的代码时,我成功地得到了用户的 response,如下所示:
import asyncio
from msgraph import GraphServiceClient
from azure.identity import UsernamePasswordCredential
credential = UsernamePasswordCredential(
client_id="appId",
username="[email protected]",
password="xxxxxxxxxx",
)
scopes=['User.Read.All']
client = GraphServiceClient(credential, scopes=scopes)
async def get_users():
try:
users = await client.users.get()
for user in users.value:
print(user.display_name)
except Exception as e:
print(e)
asyncio.run(get_users())
回复: