Python Azure Graph:访问令牌丢失或格式错误

Python Azure Graph: Access Token missing or malformed

我正在尝试通过 Azure Graph API 访问有关 AD 网络上用户的一些信息。代码如下所示:

from azure.common.credentials import ServicePrincipalCredentials
from azure.graphrbac import GraphRbacManagementClient

TENANT = 'something.onmicrosoft.com'
TENANT_ID = '...'
CLIENT_ID = '...'
SECRET = '...'

credentials = ServicePrincipalCredentials(
    client_id=CLIENT_ID,
    secret=SECRET,
    tenant=TENANT,
)
client = GraphRbacManagementClient(credentials, TENANT_ID)

client.users.list().next()

凭据没有失败,但我还是收到以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/ifs/home/.../.local/lib/python2.7/site-packages/msrest/paging.py", line 121, in __next__
    self.advance_page()
  File "/ifs/home/.../.local/lib/python2.7/site-packages/msrest/paging.py", line 107, in advance_page
    self._response = self._get_next(self.next_link)
  File "/ifs/home/.../.local/lib/python2.7/site-packages/azure/graphrbac/operations/users_operations.py", line 158, in internal_paging
    raise models.GraphErrorException(self._deserialize, response)
azure.graphrbac.models.graph_error.GraphErrorException: Access Token missing or malformed.

您在代码中遗漏了 resource。尝试使用以下代码:

from azure.common.credentials import ServicePrincipalCredentials
from azure.graphrbac import GraphRbacManagementClient

TENANT = 'something.onmicrosoft.com'
TENANT_ID = '...'
CLIENT_ID = '...'
SECRET = '...'

credentials = ServicePrincipalCredentials(
    client_id=CLIENT_ID,
    secret=SECRET,
    tenant=TENANT_ID,
    resource="https://graph.windows.net"
)
client = GraphRbacManagementClient(credentials, TENANT)

client.users.list().next()

您还可以通过 this doc 中的 Python 查看有关使用 Azure Active Directory Graph Rbac API 的更多详细信息。

如果有帮助请告诉我!