From 758f9e84058e0560cfae366d8a190274b0b51330 Mon Sep 17 00:00:00 2001 From: wpanda Date: Wed, 4 Feb 2026 13:31:20 +0100 Subject: [PATCH] get app permission --- Doc/Aufgabe.md | 4 + Doc/drucker-aufgabe.md | 12 +++ Scripts/python/Microsoft Grap Api.py | 109 +++++++++++++++++++++++ Scripts/python/get_app_permissions.py | 75 ++++++++++++++++ Scripts/python/get_app_permissions_de.py | 75 ++++++++++++++++ Scripts/python/get_token.py | 42 +++++++++ 6 files changed, 317 insertions(+) create mode 100644 Scripts/python/Microsoft Grap Api.py create mode 100644 Scripts/python/get_app_permissions.py create mode 100644 Scripts/python/get_app_permissions_de.py create mode 100644 Scripts/python/get_token.py diff --git a/Doc/Aufgabe.md b/Doc/Aufgabe.md index 388b761..ed77cfb 100644 --- a/Doc/Aufgabe.md +++ b/Doc/Aufgabe.md @@ -12,5 +12,9 @@ https://www.tc-telefon.de/Kontakt/ 7. Drucker Alster +8. Anrufen Fabio wegen die Donau Drucker Toner lvl 18% + + + j.berg 1234 diff --git a/Doc/drucker-aufgabe.md b/Doc/drucker-aufgabe.md index 5b1fc71..58f6bc1 100644 --- a/Doc/drucker-aufgabe.md +++ b/Doc/drucker-aufgabe.md @@ -27,3 +27,15 @@ Ahr_Struensee-Haus + Siede + Zorge Elbe 01 - Stuensee - Haus + + +Auf Elbe: ++ Elena Rattelmüller ++ Gloria Blewussi ++ Sarah Bidar ++ Kevin Vischer ++ Saskia Koiteck ++ Tamara Look ++ Marie Kopte ++ Vanessa Mettenbrink ++ Anne Häusler diff --git a/Scripts/python/Microsoft Grap Api.py b/Scripts/python/Microsoft Grap Api.py new file mode 100644 index 0000000..4188701 --- /dev/null +++ b/Scripts/python/Microsoft Grap Api.py @@ -0,0 +1,109 @@ +# Microsoft Graph API +import asyncio +import json +from azure.identity.aio import ClientSecretCredential +from msgraph import GraphServiceClient + +async def main(): + # Helyettesítsd a saját adataiddal + tenant_id = "tenantID" + client_id = "clientID" + client_secret = "clientSecret" + + # Credential létrehozása + credential = ClientSecretCredential(tenant_id, client_id, client_secret) + + # Graph client létrehozása + graph_client = GraphServiceClient(credential) + + try: + # Bejelentkezett felhasználó adatainak lekérése + print("Bejelentkezett felhasználó adatai:") + user = await graph_client.me.get() + print(f" Név: {user.display_name}") + print(f" Email: {user.mail or user.user_principal_name}") + print(f" ID: {user.id}") + + # Jogosultságok (permission scopes) lekérése + print("\nJogosultságok ellenőrzése...") + + # Service principal lekérése + sp = await graph_client.serviceprincipals.get(request_configuration={ + "query_parameters": {"filter": f"appId eq '{client_id}'"} + }) + + if sp.value: + app_sp = sp.value[0] + print(f"\nAlkalmazás neve: {app_sp.display_name}") + print(f"App ID: {app_sp.app_id}") + + # App role assignments lekérése + try: + app_role_assignments = await graph_client.serviceprincipals[app_sp.id].app_role_assignments.get() + + print("\nEngedélyezett app role jogosultságok:") + if app_role_assignments.value: + for assignment in app_role_assignments.value: + print(f" - Resource ID: {assignment.resource_display_name or assignment.resource_id}") + print(f" App Role ID: {assignment.app_role_id}") + print(f" Principal Type: {assignment.principal_type}") + print(f" Granted To: {assignment.principal_display_name}") + print() + else: + print(" Nincsenek app role jogosultságok beállítva") + except Exception as e: + print(f" App role lekérési hiba: {e}") + + # OAuth2 permission scopes lekérése + try: + oauth2_permission_grants = await graph_client.serviceprincipals[app_sp.id].oauth2_permission_grants.get() + + print("\nEngedélyezett OAuth2 permission scopes:") + if oauth2_permission_grants.value: + for grant in oauth2_permission_grants.value: + print(f" - Client ID: {grant.client_id}") + print(f" Consent Type: {grant.consent_type}") + print(f" Scopes: {grant.scope}") + print() + else: + print(" Nincsenek OAuth2 permission scope-ok beállítva") + except Exception as e: + print(f" OAuth2 permission lekérési hiba: {e}") + + # Current user permissions lekérése + try: + print("\nJelenlegi felhasználó jogosultságai:") + me = await graph_client.me.get() + + # User memberof check + memberof = await graph_client.me.member_of.get() + if memberof.value: + print(" Csoporttagságok:") + for group in memberof.value: + print(f" - {group.display_name}") + + # User app role assignments + user_app_roles = await graph_client.me.app_role_assignments.get() + if user_app_roles.value: + print(" Felhasználó app role jogosultságai:") + for role in user_app_roles.value: + print(f" - {role.resource_display_name}: {role.app_role_id}") + + except Exception as e: + print(f" Felhasználói jogosultságok lekérési hiba: {e}") + + # Alapvető API hívás teszt + print("\nAPI hívás teszt:") + users = await graph_client.users.get(request_configuration={ + "query_parameters": {"top": 5} + }) + print(f" Felhasználók száma: {len(users.value) if users.value else 0}") + + except Exception as e: + print(f"Hiba történt: {e}") + + finally: + await credential.close() + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/Scripts/python/get_app_permissions.py b/Scripts/python/get_app_permissions.py new file mode 100644 index 0000000..ce5cdbb --- /dev/null +++ b/Scripts/python/get_app_permissions.py @@ -0,0 +1,75 @@ +import os +import requests +import msal +import json + +# ============================================================================== +# KONFIGURATION +# ============================================================================== +TENANT_ID = "caee3499-03f8-4175-9fa8-a935248d0ece" +CLIENT_ID = "3a08b279-1fc3-419f-a77e-31f12a0f65f7" +CLIENT_SECRET = "Rk-8Q~nJ.sZ-xUiNxtEDdzVgoFFosODLVHX~jdrh" + +GRAPH_API_ENDPOINT = "https://graph.microsoft.com/v1.0" +AUTHORITY_URL = f"https://login.microsoftonline.com/{TENANT_ID}" +SCOPES = ["https://graph.microsoft.com/.default"] + +def get_access_token(): + """Acquires an access token using client credentials flow.""" + app = msal.ConfidentialClientApplication( + CLIENT_ID, + authority=AUTHORITY_URL, + client_credential=CLIENT_SECRET + ) + result = app.acquire_token_for_client(scopes=SCOPES) + if "access_token" in result: + return result["access_token"] + else: + raise Exception(f"Could not acquire access token: {result.get('error_description')}") + +def get_application_permissions(access_token, app_id): + """ + Retrieves the appRoles (permissions) for a given application (service principal). + """ + headers = { + 'Authorization': 'Bearer ' + access_token, + 'Content-Type': 'application/json' + } + # Construct the URL to query the service principal by appId and select appRoles + url = (f"{GRAPH_API_ENDPOINT}/servicePrincipals?" + f"$filter=appId+eq+'{app_id}'&" + f"$select=displayName,appId,appRoles") + + response = requests.get(url, headers=headers) + response.raise_for_status() # Raise an exception for HTTP errors + return response.json() + +if __name__ == "__main__": + try: + print("Acquiring access token...") + token = get_access_token() + print("Access token acquired.") + + print(f"Retrieving permissions for application (Client ID: {CLIENT_ID})...") + service_principal_data = get_application_permissions(token, CLIENT_ID) + + if service_principal_data and service_principal_data.get('value'): + for sp in service_principal_data['value']: + print(f"\nApplication Display Name: {sp.get('displayName')}") + print(f"Application ID: {sp.get('appId')}") + app_roles = sp.get('appRoles', []) + if app_roles: + print("Application Permissions (appRoles):") + for role in app_roles: + print(f" - Display Name: {role.get('displayName')}") + print(f" Description: {role.get('description')}") + print(f" Value: {role.get('value')}") + print(f" ID: {role.get('id')}") + print(f" IsEnabled: {role.get('isEnabled')}") + else: + print("No application permissions (appRoles) found for this service principal.") + else: + print("No service principal found with the given Client ID or no data returned.") + + except Exception as e: + print(f"An error occurred: {e}") diff --git a/Scripts/python/get_app_permissions_de.py b/Scripts/python/get_app_permissions_de.py new file mode 100644 index 0000000..de49509 --- /dev/null +++ b/Scripts/python/get_app_permissions_de.py @@ -0,0 +1,75 @@ +import os +import requests +import msal +import json + +# ============================================================================== +# KONFIGURATION +# ============================================================================== +TENANT_ID = "caee3499-03f8-4175-9fa8-a935248d0ece" +CLIENT_ID = "3a08b279-1fc3-419f-a77e-31f12a0f65f7" +CLIENT_SECRET = "Rk-8Q~nJ.sZ-xUiNxtEDdzVgoFFosODLVHX~jdrh" + +GRAPH_API_ENDPOINT = "https://graph.microsoft.com/v1.0" +AUTHORITY_URL = f"https://login.microsoftonline.com/{TENANT_ID}" +SCOPES = ["https://graph.microsoft.com/.default"] + +def get_access_token(): + """Ruft ein Zugriffstoken mittels Client-Anmeldeinformationen-Fluss ab.""" + app = msal.ConfidentialClientApplication( + CLIENT_ID, + authority=AUTHORITY_URL, + client_credential=CLIENT_SECRET + ) + result = app.acquire_token_for_client(scopes=SCOPES) + if "access_token" in result: + return result["access_token"] + else: + raise Exception(f"Zugriffstoken konnte nicht abgerufen werden: {result.get('error_description')}") + +def get_application_permissions(access_token, app_id): + """ + Ruft die appRoles (Berechtigungen) für eine gegebene Anwendung (Dienstprinzipal) ab. + """ + headers = { + 'Authorization': 'Bearer ' + access_token, + 'Content-Type': 'application/json' + } + # Erstellt die URL, um den Dienstprinzipal anhand der appId abzufragen und appRoles auszuwählen + url = (f"{GRAPH_API_ENDPOINT}/servicePrincipals?" + f"$filter=appId+eq+'{app_id}'&" + f"$select=displayName,appId,appRoles") + + response = requests.get(url, headers=headers) + response.raise_for_status() # Löst eine Ausnahme für HTTP-Fehler aus + return response.json() + +if __name__ == "__main__": + try: + print("Zugriffstoken wird abgerufen...") + token = get_access_token() + print("Zugriffstoken erfolgreich abgerufen.") + + print(f"Berechtigungen für Anwendung (Client ID: {CLIENT_ID}) werden abgerufen...") + service_principal_data = get_application_permissions(token, CLIENT_ID) + + if service_principal_data and service_principal_data.get('value'): + for sp in service_principal_data['value']: + print(f"\nAnzeigename der Anwendung: {sp.get('displayName')}") + print(f"Anwendungs-ID: {sp.get('appId')}") + app_roles = sp.get('appRoles', []) + if app_roles: + print("Anwendungsberechtigungen (appRoles):") + for role in app_roles: + print(f" - Anzeigename: {role.get('displayName')}") + print(f" Beschreibung: {role.get('description')}") + print(f" Wert: {role.get('value')}") + print(f" ID: {role.get('id')}") + print(f" Aktiviert: {role.get('isEnabled')}") + else: + print("Keine Anwendungsberechtigungen (appRoles) für diesen Dienstprinzipal gefunden.") + else: + print("Kein Dienstprinzipal mit der angegebenen Client ID gefunden oder keine Daten zurückgegeben.") + + except Exception as e: + print(f"Ein Fehler ist aufgetreten: {e}") diff --git a/Scripts/python/get_token.py b/Scripts/python/get_token.py new file mode 100644 index 0000000..53098c8 --- /dev/null +++ b/Scripts/python/get_token.py @@ -0,0 +1,42 @@ +import requests +import json +import os + +TENANT_ID = os.environ.get("AZURE_TENANT_ID") +CLIENT_ID = os.environ.get("AZURE_CLIENT_ID") +CLIENT_SECRET = os.environ.get("AZURE_CLIENT_SECRET") + +SCOPE = "https://graph.microsoft.com/.default" +TOKEN_URL = f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token" + +def get_access_token(): + headers = { + "Content-Type": "application/x-www-form-urlencoded" + } + data = { + "grant_type": "client_credentials", + "client_id": CLIENT_ID, + "client_secret": CLIENT_SECRET, + "scope": SCOPE + } + + try: + response = requests.post(TOKEN_URL, headers=headers, data=data) + response.raise_for_status() + token_data = response.json() + access_token = token_data.get("access_token") + if access_token: + print(access_token) + return access_token + else: + print(f"Error: 'access_token' not found in response. Response: {token_data}", file=os.sys.stderr) + return None + except requests.exceptions.RequestException as e: + print(f"Error making request to Azure AD: {e}", file=os.sys.stderr) + if hasattr(response, 'status_code'): + print(f"Response status code: {response.status_code}", file=os.sys.stderr) + print(f"Response body: {response.text}", file=os.sys.stderr) + return None + +if __name__ == "__main__": + get_access_token()