[Django]-How to access the Azure AD Groups and user details using python?

8👍

You can try something like the below

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 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)
👤Krassy

0👍

Header seems incorrect in this code and missing “Bearer” as this is a REST call you need to make sure header information matches with the requirement for making a REST call which is like below :-

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

Please refer to Operations on groups | Graph API reference which has Python Sample to work with Groups using Graph API.

Leave a comment