【问题标题】:How to access the Azure AD Groups and user details using python?如何使用 python 访问 Azure AD 组和用户详细信息?
【发布时间】:2018-08-15 13:18:45
【问题描述】:
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()

但我收到以下错误:

连接尝试失败,因为连接方在一段时间后没有正确响应,或者连接失败,因为连接的主机没有响应

【问题讨论】:

    标签: django python-2.7 adal


    【解决方案1】:

    你可以试试下面的方法

    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)
    

    【讨论】:

      【解决方案2】:

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

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

      请参阅Operations on groups | Graph API reference,其中有 Python 示例,可以使用 Graph API 处理组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-27
        • 2020-11-16
        • 1970-01-01
        相关资源
        最近更新 更多