2

Using the Azure Python SDK I'm trying to build a script that will audit our various user role authorizations. I'm able to pull a list of role assignments using the following:

authorizationClient = AuthorizationManagementClient(credential, subscription_id)
roles = authorizationClient.role_assignments.list()

This works, and I get a list of dicts that seems to have every piece of info I need except the principal_name. Example response:

{'additional_properties': {}, 'id': '/providers/Microsoft.Management/managementGroups/<group_ID>/providers/Microsoft.Authorization/roleAssignments/<role_ID>', 'name': '<role_ID>', 'type': 'Microsoft.Authorization/roleAssignments', 'scope': '/providers/Microsoft.Management/managementGroups/<scope_ID>', 'role_definition_id': '/subscriptions/<subscription_ID>/providers/Microsoft.Authorization/roleDefinitions/<role_def_id>', 'principal_id': '<principal_ID>', 'principal_type': 'Group', 'can_delegate': None}

Using the Azure Python SDK, is there a way to look up a principal_name given a principal_id?

I've been reading through the SDK documentation for a few hours now and can't seem to find the answer. All I can find is that the azure cli spits out the principal_id and principal_name by default, but the SDK doesn't. Any help here is appreciated.

2 Answers 2

0

You need to use the azure-graphrbac package: https://pypi.org/project/azure-graphrbac/

Example of usage:

    objects = graphrbac_client.objects.get_objects_by_object_ids({
        'object_ids': [app.object_id],
        'types': ['ServicePrincipal']
    })

There is a filter syntax as well. I don't have the one that filter with ID, but that gives you an idea:

    users = graphrbac_client.users.list(
        filter="displayName eq 'Test Buddy'"
    )

The doc of graphrbac: https://azuresdkdocs.blob.core.windows.net/$web/python/azure-graphrbac/0.61.1/azure.graphrbac.html

Some extensive unittests that could help: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/graphrbac/azure-graphrbac/tests/test_graphrbac.py

The RestAPI doc could give you some insights into what the SDK can do: https://learn.microsoft.com/en-us/previous-versions/azure/ad/graph/api/api-catalog

(I work at MS in the Python SDK team)

2
  • This was exactly what I needed to get me going in the right direction, thanks!! For anyone that find this later, this requires your service principal be entitled with Azure AD Graph permissions. You can also do this with the rest api: url = f'graph.windows.net{self.AZURE_TENANT_ID}/getObjectsByObjectIds?api-version=1.6' If you proxy the azure CLI through an intercepting proxy (like burp), you'll get the authorization process and everything. Commented Nov 9, 2020 at 15:26
  • 1
    This answer helped me, but how is this affected by the Azure AD Graph API deprecation devblogs.microsoft.com/microsoft365dev/… ? Commented Jun 13, 2022 at 12:57
0

A full Python example:

# requirements.txt

azure-common==1.1.27
azure-core==1.19.0
azure-graphrbac==0.61.1
azure-identity==1.6.1
azure-mgmt-authorization==2.0.0
azure-mgmt-core==1.3.0
msrestazure==0.6.4
"""wrapper.py

   Copy from this answer https://stackoverflow.com/a/64129363/3324095 
"""
"""main.py"""
import sys

from azure.graphrbac import GraphRbacManagementClient
from azure.graphrbac.models import GetObjectsParameters
from azure.identity import DefaultAzureCredential
from azure.mgmt.authorization import AuthorizationManagementClient

from wrapper import CredentialWrapper

CREDENTIALS = DefaultAzureCredential()

# Without the resource_id arg, you get an error:
# msrestazure.azure_exceptions.CloudError: 401 Client Error: Unauthorized for url...
GRAPH_CREDENTIALS = CredentialWrapper(
    resource_id="https://graph.windows.net",
)


def main(tenant_id, subscription_id):
    auth_client = AuthorizationManagementClient(
        credential=CREDENTIALS, subscription_id=subscription_id
    )

    # https://learn.microsoft.com/en-us/python/api/azure-mgmt-authorization/azure.mgmt.authorization.v2015_07_01.models.roleassignmentlistresult?view=azure-python
    assignments_list = list(auth_client.role_assignments.list())

    role_definitions = list(
        auth_client.role_definitions.list(
            scope="/subscriptions/" + subscription_id
        )
    )

    # A lookup table of role definition IDs and their names.
    role_def_dict = {x.id: x.role_name for x in role_definitions}

    graph_client = GraphRbacManagementClient(
        credentials=GRAPH_CREDENTIALS, tenant_id=tenant_id
    )

    for assignment in assignments_list:
        
        # Look up the role's name using its ID.
        role_name = role_def_dict[assignment.properties.role_definition_id]

        # Barely any documentation on this function. I've lifted the code from the CLI.
        params = GetObjectsParameters(
            include_directory_object_references=True,
            object_ids=[assignment.properties.principal_id],
        )

        # Likewise this function.
        results = list(graph_client.objects.get_objects_by_object_ids(params))

        # This is the group/user/managed identity that has been assigned the role
        assignee = results[0]

        print("{} : {}".format(results[0].display_name, role_name))


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2])
python -m main "<your-tenant-id>" "<your-subscription-id>"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.