如何使用python访问Azure AD组和用户详细信息?

时间:2018-08-15 13:18:46

标签: django python-2.7 adal

params = urllib.urlencode({
    # Specify values for the following required parameters
    'api-version': '1.5',
    'tenant_id':'vvvvvvvvXXXXXX',
})

headers = { 'Authorization':'TzmMKl1QoxWjvPyX8Xv79ZxvZgoGHwbRt3ZQXwNoFBu42R6yj0o4aMraEVkNkoLyvN8KZjDi4mD7w41gTREsUhbOyg_PsUEv7g4SoTsbRluj8hHrrWuXj8h32MyklOB7ahAKBRLE8KAcmVARdb4vpQ'

}
try:
        conn = httplib.HTTPSConnection('graph.windows.net')
        print("got connection and getting it to actual domain")
        print(conn)
        conn.request("GET", "/{tenent_id}/groups?%s" % params, "", headers)
        response = conn.getresponse()
        data = response.read()
        print(data)
        conn.close()

但是我收到以下错误:

  

连接尝试失败是因为被连接方在一段时间后未正确响应,或者由于连接的主机未能响应而建立的连接失败

2 个答案:

答案 0 :(得分:0)

此代码中的标头似乎不正确,并且缺少“承载器”,因为这是一个REST调用,您需要确保标头信息与进行REST调用的要求相匹配,如下所示:-

headers = {'Authorization': 'Bearer ' + token}

请参阅Operations on groups | Graph API reference,该书具有Python示例,可通过Graph API与网上论坛配合使用。

答案 1 :(得分:0)

您可以尝试以下类似操作

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

credentials = ServicePrincipalCredentials(
    client_id="Your_Client_ID",
    secret="Your_Secret",
    resource="https://graph.windows.net",
    tenant = 'yourtenant.onmicrosoft.com'
)
tenant_id = 'your_tenant_id'

graphrbac_client = GraphRbacManagementClient(
    credentials,
    tenant_id
)
users = graphrbac_client.users.list()
for user in users:
     print(user.user_principal_name)

groups = graphrbac_client.groups.list()
for g in groups:
     print(g.display_name)

或使用ADAL和请求

import adal,requests

url = 'https://login.microsoftonline.com/yourtenant.onmicrosoft.com/oauth2/v2.0/token'
data = {
    'grant_type': 'client_credentials',
    'client_id': "your_client_id",
    'scope': 'https://graph.microsoft.com/.default',
    'client_secret': "your_client_secret"
}
r = requests.post(url, data=data)
token = r.json().get('access_token')

url = 'https://graph.microsoft.com/v1.0/users'
#url = 'https://graph.microsoft.com/beta/groups'
headers = {
    'Content-Type' : 'application\json',
    'Authorization': 'Bearer {}'.format(token)
}
r = requests.get(url, headers=headers)
result = r.json()
print(result)