且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-04 09:30:34

你可以试试下面的方法

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)

OR 使用 ADAL 和请求


OR Using ADAL and Requests

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)