1

I am having some challenges getting the application owner of each application registration. Anyone have any insight? Here is a snippet of the code i'm using.

import logging
import requests
import datetime
from datetime import timezone
from dateutil.parser import parse

def get_application_owner(graph_client, app_id):
    """
    Retrieve owner of the Azure Application using Microsoft Graph Client.
    """
    # Get the application registration details
    application = graph_client.get(f"/applications/{app_id}")
    application_json = application.json()
    owner_object_id = application_json.get('appOwnerOrganizationId')

    if owner_object_id:
        # Retrieve the owner's details
        owner = graph_client.get(f"/users/{owner_object_id}")
        owner_json = owner.json()
        return owner_json.get('displayName', 'N/A')
    else:
        return 'N/A'

credential = ClientSecretCredential(tenant_id,client_id,client_secret)       

graph_base_url = "https://graph.microsoft.com/v1.0"
graph_client = GraphClient(credential=credential)   

graph_url="/v1.0/serviceprincipals"
response = graph_client.get(graph_url)

service_principals = response.json().get('value', [])
        for app in service_principals:
            app_id = app.get('appId')
            owner_object_id = app.get('appOwnerOrganizationId')
            owner_name = 'N/A'
            
            if owner_object_id:
                owner = graph_client.objects.get_object_by_object_id(owner_object_id)
                owner_name = owner.display_name
                
            secrets = app.get('passwordCredentials', [])
            for secret in secrets:
                end_date_str = secret.get('endDateTime', None)
                if end_date_str:
                    end_date = parse(end_date_str)
                    if end_date <= expiry_threshold:
                        human_friendly_date = end_date.strftime('%Y-%m-%d %H:%M:%S %Z')
                        expiring_secrets.append({
                            'displayName': app.get('displayName'),
                            'secretId': secret.get('keyId'),
                            'expiryDate': human_friendly_date,
                            'owner': owner_name
                        })

I've used these libraries above but I do not get the owner as expected:

1 Answers1

0

Add Azure application owners using python

You can use the below code to add an owner to your enterprise application and also you can fetch the details of the owner of the App registration.

Make sure before running the code proper Api permission **Application.ReadWrite.All*(Application).

Code:

import requests
import json
from azure.identity import ClientSecretCredential
import requests

tenant_id = "Your-tenant-id"
client_id = "Your-application-id"
client_secret = "your-client-secret"
credential = ClientSecretCredential(tenant_id, client_id, client_secret)

graph_url = "https://graph.microsoft.com/v1.0"
access_token = credential.get_token("https://graph.microsoft.com/.default").token

api_endpoint = 'https://graph.microsoft.com/v1.0/servicePrincipals/appId=xxxxx/owners/$ref' #applicationid

# Set the request headers
headers = {
    'Authorization': 'Bearer ' + access_token,
    'Content-Type': 'application/json'
}

# Set the request body
body = {
    '@odata.id': 'https://graph.microsoft.com/v1.0/directoryObjects/<user-object-id>'
}

response = requests.post(api_endpoint, headers=headers, data=json.dumps(body))
print(response.text)

if response.status_code == 204:
    print('Owner added successfully.')
else:
    print('Error adding owner.')
    

api_endpoint = 'https://graph.microsoft.com/v1.0/servicePrincipals/appId=xxxx/owners'
response = requests.get(api_endpoint, headers=headers)

# Check the response status code
if response.status_code == 200:
    app_details = response.json()
    s = json.dumps(app_details)
    q = json.dumps(json.loads(s), indent=2)
    print(q)
else:
    print('Error fetching application details.')

Output:

Owner added successfully.
{
  "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#directoryObjects",
  "value": [
    {
      "@odata.type": "#microsoft.graph.user",
      "id": "xxxxxxxxx",
      "businessPhones": [],
      "displayName": "venkattestuser",
      "givenName": null,
      "jobTitle": null,
      "mail": null,
      "mobilePhone": null,
      "officeLocation": null,
      "preferredLanguage": null,
      "surname": null,
      "userPrincipalName": "venkaxxxxxxxxx.onmicrosoft.com"
    }
  ]
}

enter image description here

Portal:

enter image description here

Reference:

Venkatesan
  • 3,748
  • 1
  • 3
  • 15