ChristofferL
ChristofferL

Reputation: 119

Use Graph API with System Assigned Managed Identity in Azure Function (Python)

I have successfully added application permissions to my system assigned Managed Identity/Service principal/MSI (Enterprise app) connected to a Azure Function through the following guide.

https://gist.githubusercontent.com/JanVidarElven/32b8f6bb8a422c9cce1816582eef24d8/raw/1148f1a96a351acf1a0fcf282e187ef1d2398fb1/AddManagedIdentityMSGraphAppRoles.md

I have previously used a separately created App registration/Enterprise app and used a secret from it to acquire a token to use when sending requests to Microsoft Graph API.

def get_auth_token_appreg(secret):
app = msal.ConfidentialClientApplication(appreg_client_id, authority=appreg_tenant_id, client_credential=secret)

result = None
result = app.acquire_token_silent(default_scope, account=None)

if not result:
    result = app.acquire_token_for_client(default_scope)

return result["access_token"]

I can't figure out how (if it's possible) to use this MSI without using a app registration secret in Python. Since there is no app registration I'm not even sure I can't get a secret for this MSI. I don't want a to use a secret but rather utilize the MSI (with it's permissions) instead since a secret kinda defeats the purpose of adding permissions to the MSI.

Any ideas?

Upvotes: 2

Views: 2826

Answers (1)

ChristofferL
ChristofferL

Reputation: 119

Got it working with some help in the comments.

Add permissions to the managed identity, it can be found in the Enterprise app's list if you change Application type to Managed Identity.

Powershell guide to add permissions:

https://gist.githubusercontent.com/JanVidarElven/32b8f6bb8a422c9cce1816582eef24d8/raw/1148f1a96a351acf1a0fcf282e187ef1d2398fb1/AddManagedIdentityMSGraphAppRoles.md

Python code to issue a token:

default_scope = "https://graph.microsoft.com/.default"

def get_token():
credential = DefaultAzureCredential()
token = credential.get_token(default_scope)
return token[0]

Make sure that the token that is issued has the correct roles/permissions. You can use https://jwt.ms/ to check the token.

Upvotes: 3

Related Questions