user18148705
user18148705

Reputation: 325

How to access azure AD using python SDK

I am new to Azure, I want to write a python function to access Azure AD and list the existing groups there, I am facing issues logging into azure. I have been working in AWS there I use boto3 as SDK and I use the command line or programmatic acess. Following is the code that I have

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

# See above for details on creating different types of AAD credentials
credentials = UserPassCredentials(
            '[email protected]',      # The user id I use to login into my personal account
            'my_password',          # password of that account 
            resource="https://graph.windows.net"
    )

tenant_id = "82019-1-some-numbers"

graphrbac_client = GraphRbacManagementClient(
    credentials,
    tenant_id
)

I want to know which is professional way of logging into azure, how do i list the groups present in my azure AD, what code changes do i have to do for that

Snapshot of the API permission enter image description here

Upvotes: 4

Views: 3869

Answers (1)

Rukmini
Rukmini

Reputation: 15444

To retrieve list of Azure AD groups, make sure to grant Directory.Read.All for your application like below:

Go to Azure Portal -> Azure Active Directory -> App Registrations -> Your App -> API permissions

enter image description here

You can make use of below script to get the list of Azure AD Groups by Krassy in this SO Thread:

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

credentials = ServicePrincipalCredentials(
    client_id="Client_ID",
    secret="Secret",
    resource="https://graph.microsoft.com",
    tenant = 'tenant.onmicrosoft.com'
)
tenant_id = 'tenant_id'
graphrbac_client = GraphRbacManagementClient(credentials,tenant_id)
groups = graphrbac_client.groups.list()
for g in groups:
     print(g.display_name)

For more in detail, please refer below links:

Azure Python SDK - Interact with Azure AD by Joy Wang

How to access the list of Azure AD Groups using python by Will Shao - MSFT

Upvotes: 3

Related Questions